The problem context involves a game where a player can move through an array either by taking a single step to an adjacent index, or by making a 'leap' of a specified distance. The array is filled with zeroes and ones, where zero represents a valid move and one represents a blocked index. The player wins if they can reach the end of the array or move beyond it.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution uses a recursive approach to check all possible moves from each index. It starts from the first index and checks if a win is possible by moving one step forward, leaping, or moving one step backward. If any of these moves leads to a win, it returns true. If a move leads to an index that has already been visited or is blocked, it returns false. The recursion ends when all possible moves have been checked.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.datastructures;
import java.util.Scanner;
/**
*
*/
public class Java1DArrayPart2 {
public static boolean canWin(int leap, int[] game) {
return canWin(leap, game, 0);
}
public static boolean canWin(int leap, int[] g, int i) {
if (i < 0 || g[i] == 1) {
return false;
}
if (i + leap >= g.length || i == g.length - 1) {
return true;
}
g[i] = 1;
return canWin(leap, g, i + 1) || canWin(leap, g, i + leap) || canWin(leap, g, 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)) ? "YES" : "NO");
}
scan.close();
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.