Java 1D Array (Part 2) – Hacker Rank Solution

Java 1D Array (Part 2) - Hacker Rank Solution
Java 1D Array (Part 2) – Hacker Rank Solution

Problem :

Let’s play a game on an array! You’re standing at index  of an -element array named . From some index  (where ), you can perform one of the following moves:

  • Move Backward: If cell  exists and contains a , you can walk back to cell .

Problem Statement: Click Here



Java 1D Array (Part 2) – Hacker Rank Solution

import java.util.*;
public class Solution {
    public static boolean canWin(int leap, int[] game, int i) {
        if (i < 0 || game[i] == 1)
            return false;
        if (i + 1 >= game.length || i + leap >= game.length)
            return true;
        game[i] = 1; //flag
        return canWin(leap, game, i + leap)
                || canWin(leap, game, i + 1)
                || canWin(leap, game, i - 1);
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int q = scan.nextInt();
        while (q-- > 0) {
            int n = scan.nextInt();
            int leap = scan.nextInt();
            int[] game = new int[n];
            for (int i = 0; i < n; i++) {
                game[i] = scan.nextInt();
            }
            System.out.println((canWin(leap, game, 0)) ? "YES" : "NO");
        }
        scan.close();
    }
}

Disclaimer: The above Problem (Java 1D Array (Part 2)) is generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.

Leave a Comment