We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicstaticbooleancanWin(intleap,int[]game){returnisSolvable(leap,game,0);}privatestaticbooleanisSolvable(intleap,int[]game,inti){// Base Casesif(i>=game.length){returntrue;}elseif(i<0||game[i]==1){returnfalse;}game[i]=1;// marks as visited// Recursive CasesreturnisSolvable(leap,game,i+leap)||isSolvable(leap,game,i+1)||isSolvable(leap,game,i-1);}
Our array is of size 6, our step size m = 5, and the array is shown above.
We start at index 0.
First, it tries to take a step of size 5, and fails (since there's a 1 there). Then it tries taking a step forward "i+1", and it works (since there's a 0 there). So now we're at index 1 in the array.
Now it can take a leap of size m = 5, and succeed.
I see your solution, but which question is that? If it's in any of the following tracks:
10 Days of Statistics
30 Days of Code
Algorithms
Cracking the Coding Interview
Data Structures
Java
then I may already have posted the solution in HackerRank solutions. If it's a question from any of those tracks I can go ahead and try to solve it for you. If it's from a different track I can get to it after I finish completing the above tracks.
From index 1,how can u take a leap 5?
As per question, lead can be added only if the destination value is zero.
But here, (index1) 0 + 5 (leap) = 1(index 5) -where the destination value is not zero. Then, how can this move be possible?
hello rshaghoulian............. your approach is efficent and understandable for others......... u r doing a great job for newcommers. thanks a lot for pretty solution
Hi. Are you looking for a solution to the array rotation problem? If so, I have seen this as 3 different HackerRank problems and have posted solutions in my HackerRank solutions. Just search "rotation" on the linked page and you will find it.
Good question. Let n be # of elements in our array. The time complexity is O(n) since we visit each element in the array a maximum of 1 times. (Technically, we do sometimes revisit an element, but since we already marked it as visited, we immediatelly return, so this only adds a constant factor to our runtime)
Hi. At each spot in the array, we have 3 options. The code tries all 3 paths for each spot in the array. If any of them lead to a solution, we return true, otherwise, false.
Could you please explain why the recursive function will perform all these 3 steps. It should perform just 1 because others are in "OR".
So it should be either to one position forward, or direct to the (index+leap) position or 1 step backword.
Could you pleae explain the working of that return statement.
My Code does not working out well.So, What should I do right now.Please tell me because I am still struggling to solve this programming question, Since 1 hours.
Hi. As a first step I would recommend trying to understand the solution I posted above. You can then compare my solution to yours to see what we're doing differently, so you can find any bugs.
Hi, I'm confused with the value at current index
eg:
test case
1
5 3
1 0 0 0 0 --> I can leap to i+1 || i+3(leap) -- if arr[i+3]||[i+1]==0.
i dont see that if i start at index 0 and it has a value 1(not a constraint basedon the question), does'nt make a move
Hi. I took a look at the code and couldn't a bug. Your main() function seems fine to me (You create a slightly bigger game[] function than I do so you can leap to the end, but that seems fine). Your recursive cases Also add/subtract from "i" properly. There must be some base case or off-by-1 error. My suggestion is to find the exact test case that fails and to walk through it by hand to see what your code does. That will work much better than trying to reason through the code.
I've made a correction in my code and the output for ibexxx's input is 'YES'.I just exchanged the first if statement and the else if statement following it. Yet the 5 testcases fail.
I changed these lines
Your code fails because there is no retracing of paths possible incase you got stuck on any square. To retrace the path, use a stack. Pop the elements out of the stack only after verifying game[i+1],game[i-1] and game[i+leap] has a 0 or not.
The problem is that you greedily always go forward as much as possible if you can and this is incorrect. Just because you can leap doesn't mean you should. Lets take the following scenario:
leap = 4 and 0 0 0 1 0 1 0 1 1 1 0
You would leap from the 0th index to the 4th (the first zero in between 1's). You would then be stuck and you would falsely return that this game cannot be won. However, you should walk to i = 2, then leap to the second 0 (in between 1s), then finally leap to the end of the board.
This is why the recursive solutions work, if leaping fails, then they try to go back, if that fails, they try to go forward (or in whatever order they put them in). If all three fail, you can't win.
To fix your code, you need to do two things: 1) you need to have a way to try and go forward (and leap from there) and 2) you need to have a way to try and go backwards (and leap from there).
My code has passed 5 test cases . it is failing the test cases which has 5000 test cases . does this has to do any thing with that ??i even tried running 5000 test cases but i am getting output for 1473 records can any body try my code and tell me atleast what is happening and why just 1473 test cases are executing ????? +rshaghoulian(appriciate if you can help me)
Is it failing? Or is it timing out? It's important to know which one is happening. If it's failing on 5000 test cases, there may not be a bug with the code, you may just need a faster algorithm.
rshaghoulian thanks man . i guess u are the only person who are so active in these discussions ? do you have any idea how many people are actually follwing this website ? i am asking as i just joined this website .
it's not working even if i copy pasted by the solution......error showing that cannot find symbol and method anWin cannot applied to the given type.....?
what is the problem i have no idea
Could you please explain why the recursive function will perform all these 3 steps. It should perform just 1 because others are in "OR". So it should be either to one position forward, or direct to the (index+leap) position or 1 step backword.
Could you pleae explain the working of that return statement.
Replace the canWin() function in the sample code with this code and it will work. Make sure to leave the main() function in the original code too. I just tested it and it works.
}
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();
visited=new int[n];
int[] game = new int[n];
for (int i = 0; i < n; i++) {
game[i] = scan.nextInt();
}
hank you so much for this. I was into this issue and tired to tinker around to check if its https://plex.software possible but couldnt get it done. Now that i have seen the way you did it, thanks guys
with
regards
Thanks for sh https://kodi.software/ aring.I found a lot of interesting information here. A really good post, very thankful and hopeful that you will write many more posts like this one.
As hybrid application development with the mobile industry has a steady rise, mobile application development has become increasingly competitive. The pervasiveness of mobile devices and the widespread use of mobile applications among the global population has made smartphones a perfect avenue through which businesses can interact with their customers and clients. Companies can offer their products and services via mobile apps and significantly increase their customer base. As a result, the role of mobile application development in driving the growth of businesses has never been more important.
Nice.. I like how you have used comments to show exactly what the base cases and recursive cases are. Also, writing the three recursive cases on three separate lines makes the solution neater and easier to read. 10/10
Java 1D Array (Part 2)
You are viewing a single comment's thread. Return to all comments →
Java solution - passes 100% of test cases
Solution is basically to do a depth-first search (DFS). Instead of creating a "visited" array, we can mark each array value as 1 when visiting it.
Full code available at my HackerRank solutions. Here is the main snippet:
Let me know if you have any questions.
çould you please tell the flow of this recursion? with values
Here's a test case from the problem:
Our array is of size 6, our step size m = 5, and the array is shown above.
We start at index 0.
First, it tries to take a step of size 5, and fails (since there's a 1 there). Then it tries taking a step forward "i+1", and it works (since there's a 0 there). So now we're at index 1 in the array.
Now it can take a leap of size m = 5, and succeed.
HackerRank solutions.
Hi, I am facing problem while soving it .Can you provide the generilized solution or algo for it.
https://github.com/rsamrat073/HackerRank/blob/master/ArrayHopping
I see your solution, but which question is that? If it's in any of the following tracks:
then I may already have posted the solution in HackerRank solutions. If it's a question from any of those tracks I can go ahead and try to solve it for you. If it's from a different track I can get to it after I finish completing the above tracks.
Same problem which we all are solving.I need suggestion in my code
Great explanation, thanks.
Thanks. But why is it trying to do the third recursion(isSolvable(array, m, i - 1)) first?
I updated/fixed my original explanation.
HackerRank solutions
You explained perfectly :]
From index 1,how can u take a leap 5? As per question, lead can be added only if the destination value is zero. But here, (index1) 0 + 5 (leap) = 1(index 5) -where the destination value is not zero. Then, how can this move be possible?
A leap of 5 from index 1 will take you off the end of the array, thus you win.
You are a genious man !!
lol thanks I guess.
hello rshaghoulian............. your approach is efficent and understandable for others......... u r doing a great job for newcommers. thanks a lot for pretty solution
Sure. I'm glad you approve of my posted solution; it was a tricky one! I'm happy the solution helped :)
plz solve this Array rotaion n=5 , rotation = 4
Hi. Are you looking for a solution to the array rotation problem? If so, I have seen this as 3 different HackerRank problems and have posted solutions in my HackerRank solutions. Just search "rotation" on the linked page and you will find it.
thanks a lot sir
awesome great !!
Excellent solution sir
Can I know the overall time complexity for your solution to this problem?
Good question. Let n be # of elements in our array. The time complexity is O(n) since we visit each element in the array a maximum of 1 times. (Technically, we do sometimes revisit an element, but since we already marked it as visited, we immediatelly return, so this only adds a constant factor to our runtime)
HackerRank solutions.
Shouldn't the order be like below to finish the game quickly?.
Excellent point. Updated code. Thanks.
Hi rshaghoulian can you explain how ` return isSolvable(array, m, i + m) || isSolvable(array, m, i + 1) || isSolvable(array, m, i - 1); Is behaving
Hi. At each spot in the array, we have 3 options. The code tries all 3 paths for each spot in the array. If any of them lead to a solution, we return true, otherwise, false.
tries to take m steps right.
tries to take 1 step right.
tries to take 1 step left.
HackerRank solutions.
how can i know when the recursive case ended ?
The 4 lines code with the comment that says "Base cases" corresponds to when the recursive case ends.
HackerRank solutions.
Could you please explain why the recursive function will perform all these 3 steps. It should perform just 1 because others are in "OR". So it should be either to one position forward, or direct to the (index+leap) position or 1 step backword.
Could you pleae explain the working of that return statement.
isSolvable(array, m, i - 1) is giving ArrayIndexOutOfBoundsException ...... in the very 1st test case....
The following lines from my code should prevent that from happening:
since they check for array out of bounds.
HackerRank solutions.
My Code does not working out well.So, What should I do right now.Please tell me because I am still struggling to solve this programming question, Since 1 hours.
Hi. As a first step I would recommend trying to understand the solution I posted above. You can then compare my solution to yours to see what we're doing differently, so you can find any bugs.
HackerRank solutions.
Hi, I'm confused with the value at current index eg: test case 1 5 3 1 0 0 0 0 --> I can leap to i+1 || i+3(leap) -- if arr[i+3]||[i+1]==0. i dont see that if i start at index 0 and it has a value 1(not a constraint basedon the question), does'nt make a move
Hi. The question states "It is guaranteed that the value of game[0] is always 0", so your test case is not valid.
HackerRank solutions.
_/_
This code passes 5 TCs. I've tried it without using recursion.Please help me complete this code.
I posted it here because I would like to get the answer from you rshaghoulian
Hi. I took a look at the code and couldn't a bug. Your main() function seems fine to me (You create a slightly bigger game[] function than I do so you can leap to the end, but that seems fine). Your recursive cases Also add/subtract from "i" properly. There must be some base case or off-by-1 error. My suggestion is to find the exact test case that fails and to walk through it by hand to see what your code does. That will work much better than trying to reason through the code.
I will try it.Thanks a lot.
Your code fails on the following test case:
Hi. I ran my code with your input and it correctly printed YES. This can be done by doing jumps of 1, 1, 4, 4, 4, 4.
Full code available at HackerRank solutions.
not your code, the one from Vijay_Ravi...
I've made a correction in my code and the output for ibexxx's input is 'YES'.I just exchanged the first if statement and the else if statement following it. Yet the 5 testcases fail. I changed these lines
which makes jumps of 4,4,4 to
which makes jumps of 1,1,4,4,4.
Now your code fails on:
The change I have made to my code also does jumps of 1,1,4,4,4. Still the 5 testcases fail.
Your code fails because there is no retracing of paths possible incase you got stuck on any square. To retrace the path, use a stack. Pop the elements out of the stack only after verifying game[i+1],game[i-1] and game[i+leap] has a 0 or not.
The problem is that you greedily always go forward as much as possible if you can and this is incorrect. Just because you can leap doesn't mean you should. Lets take the following scenario:
leap = 4 and 0 0 0 1 0 1 0 1 1 1 0
You would leap from the 0th index to the 4th (the first zero in between 1's). You would then be stuck and you would falsely return that this game cannot be won. However, you should walk to i = 2, then leap to the second 0 (in between 1s), then finally leap to the end of the board.
This is why the recursive solutions work, if leaping fails, then they try to go back, if that fails, they try to go forward (or in whatever order they put them in). If all three fail, you can't win.
To fix your code, you need to do two things: 1) you need to have a way to try and go forward (and leap from there) and 2) you need to have a way to try and go backwards (and leap from there).
My code has passed 5 test cases . it is failing the test cases which has 5000 test cases . does this has to do any thing with that ??i even tried running 5000 test cases but i am getting output for 1473 records can any body try my code and tell me atleast what is happening and why just 1473 test cases are executing ????? +rshaghoulian(appriciate if you can help me)
Is it failing? Or is it timing out? It's important to know which one is happening. If it's failing on 5000 test cases, there may not be a bug with the code, you may just need a faster algorithm.
HackerRank solutions.
rshaghoulian thanks man . i guess u are the only person who are so active in these discussions ? do you have any idea how many people are actually follwing this website ? i am asking as i just joined this website .
Not sure how many people use this site, maybe 10s of thousands.
it's not working even if i copy pasted by the solution......error showing that cannot find symbol and method anWin cannot applied to the given type.....? what is the problem i have no idea
Try the full solution available at HackerRank solutions.
How can call this function in the main function?
This code is just a snippet. You can see how I call the function from main in my HackerRank solutions.
@RodneyShag
Could you please explain why the recursive function will perform all these 3 steps. It should perform just 1 because others are in "OR". So it should be either to one position forward, or direct to the (index+leap) position or 1 step backword.
Could you pleae explain the working of that return statement.
It only performs the other ones in the "OR" if the 1st one fails (as in it returns false). In that case, it tries the next condition in the OR.
HackerRank solutions.
getting eror...
Solution.java:7: error: illegal start of expression private static boolean solvable(int [] array, int m, int i) {
Hi. HackerRank had changed this question. I just updated my solution to match the altered question. Please try the new code along with Java 8.
HackerRank solutions.
how is this question related to DFS? what is DFS??
DFS is depth-first-search. Our recursive calls in the solution are DFS. I recommend reading more about depth-first-search on Google.
HackerRank solutions.
Hi bro..! I have solved this problem following your solution,but i did'nt get any pts.Tell me please what's the problem???
You can contact HackerRank about that. Don't worry about points, just try learning the concepts.
HackerRank solutions.
sir it not excuting it is showing the errors sir
Replace the
canWin()
function in the sample code with this code and it will work. Make sure to leave themain()
function in the original code too. I just tested it and it works.HackerRank solutions.
Can you please tell me what is the wrong with my code
public static boolean canWin(int leap, int[] game) { // Return true if you can win the game; otherwise, return false. int i=0; int n=game.length; while(i < n) { if((i+leap<=n-1 && game[i+leap]==0) || i+leap==n-1) i=i+leap; else if((i+1<=n-1 && game[i+1]==0) || i+1==n-1) i=i+1; else if( i-1 >=1 && game[i-1]==0 ) i=i-1; else return false; if (i==n-1) return true; } return true;}
import java.util.; import java.io.;
class Solution{ public static void main(String []argh){ int[][] arr = new int[10][10]; Scanner sc = new Scanner(System.in); for(int i=0;i<6;i++){ for(int j=0;j<6;j++){ arr[i][j]=sc.nextInt();
}
import java.util.*;
public class Solution {
static int visited[];
public static boolean canWin(int[] game,int leap,int i) { // Return true if you can win the game; otherwise, return false.
} 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(); visited=new int[n]; int[] game = new int[n]; for (int i = 0; i < n; i++) { game[i] = scan.nextInt(); }
} }
hank you so much for this. I was into this issue and tired to tinker around to check if its https://plex.software possible but couldnt get it done. Now that i have seen the way you did it, thanks guys with regards
Thanks for sh https://kodi.software/ aring.I found a lot of interesting information here. A really good post, very thankful and hopeful that you will write many more posts like this one.
As hybrid application development with the mobile industry has a steady rise, mobile application development has become increasingly competitive. The pervasiveness of mobile devices and the widespread use of mobile applications among the global population has made smartphones a perfect avenue through which businesses can interact with their customers and clients. Companies can offer their products and services via mobile apps and significantly increase their customer base. As a result, the role of mobile application development in driving the growth of businesses has never been more important.
This is pure genius, great solution.
Can You Tell me What we be the recurrence relation for this
wow that was amazing, I still can't judge where n how to use recursive function
cann you please explaine in breff
Why do we mark game[i] = 1? I know we have visited that index once, but the goal is to see if we can win or not , right?
hey! amazing solution. i was just wondering, can we use DP to solve this?
Nice.. I like how you have used comments to show exactly what the base cases and recursive cases are. Also, writing the three recursive cases on three separate lines makes the solution neater and easier to read. 10/10
This logic is soo neat. Oh my god.
could you please explain the logic to move backward i.e why i-1 ?
This is BRILLIANT. Thankyou!
pleasure is mine, Happy coding :)
Why is it false if i < 0 ?
what a beautifull use of recursion!!!
good job
This is really helpful, Thankyou So much for providing this. I am doing this one from past 1 hour, i was completely fed up with this question. Thanks.
can you please tell me about your third recursion "isSolveable(leap, game, i-1 ) ".
// Recursive Cases return isSolvable(leap, game, i + leap) || isSolvable(leap, game, i + 1) || isSolvable(leap, game, i - 1);
can anyone explain how this return statement works.
return isSolvable(leap, game, i + leap) || isSolvable(leap, game, i + 1) || isSolvable(leap, game, i - 1);