Java 1D Array (Part 2) HackerRank Solution

Hello Programmers, In this post, you will know how to solve the Java 1D Array (Part 2) HackerRank Solution. This problem is a part of the HackerRank Java Programming Series.

Java 1D Array (Part 2) HackerRank Solution
Java 1D Array (Part 2) HackerRank Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Java 1D Array (Part 2) HackerRank Solutions


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) HackerRank Solutions

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(;
        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");

Disclaimer: The above Problem (Java 1D Array (Part 2)) is generated by Hackerrank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Java List HackerRank Solution

Leave a Reply

Your email address will not be published. Required fields are marked *