Java 1D Array (Part 2)

  • + 38 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:

    public static boolean canWin(int leap, int[] game) {
        return isSolvable(leap, game, 0);
    }
    
    private static boolean isSolvable(int leap, int[] game, int i) {
        // Base Cases
        if (i >= game.length) {
            return true;
        } else if (i < 0 || game[i] == 1) {
            return false;
        }
                
        game[i] = 1; // marks as visited
    
        // Recursive Cases
        return isSolvable(leap, game, i + leap) || 
               isSolvable(leap, game, i + 1) || 
               isSolvable(leap, game, i - 1);
    }
    

    Let me know if you have any questions.

    • + 1 comment

      çould you please tell the flow of this recursion? with values

      • + 5 comments

        Here's a test case from the problem:

        6 5
        0 0 0 1 1 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.

        HackerRank solutions.

        • + 1 comment

          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

          • + 1 comment

            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.

            • + 0 comments

              Same problem which we all are solving.I need suggestion in my code

        • + 0 comments

          Great explanation, thanks.

        • + 1 comment

          Thanks. But why is it trying to do the third recursion(isSolvable(array, m, i - 1)) first?

          • + 0 comments

            I updated/fixed my original explanation.

            HackerRank solutions

        • + 0 comments

          You explained perfectly :]

        • + 1 comment

          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?

          • [deleted]
            + 0 comments

            A leap of 5 from index 1 will take you off the end of the array, thus you win.

            [1] visited
            [0] we're here
            [0] + 1
            [1] + 2
            [1] + 3
            [1] + 4
                + 5
            
    • + 1 comment

      You are a genious man !!

      • + 2 comments

        lol thanks I guess.

        • + 1 comment

          hello rshaghoulian............. your approach is efficent and understandable for others......... u r doing a great job for newcommers. thanks a lot for pretty solution

          • + 1 comment

            Sure. I'm glad you approve of my posted solution; it was a tricky one! I'm happy the solution helped :)

            • + 1 comment

              plz solve this Array rotaion n=5 , rotation = 4

                        {1,2,3,4,5}->{2,3,4,5,1}->{3,4,5,1,2}->{4,5,1,2,3}->{5,1,2,3,4}
              
              • + 1 comment

                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.

                • + 0 comments

                  thanks a lot sir

        • + 0 comments

          awesome great !!

    • + 0 comments

      Excellent solution sir

    • + 1 comment

      Can I know the overall time complexity for your solution to this problem?

      • + 0 comments

        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.

    • + 1 comment

      Shouldn't the order be like below to finish the game quickly?.

      /* Recursive Cases */
          return solvable(array, m, i + m) || 
                 solvable(array, m, i + 1) || 
                 solvable(array, m, i - 1);
      
      • + 0 comments

        Excellent point. Updated code. Thanks.

    • + 1 comment

      Hi rshaghoulian can you explain how ` return isSolvable(array, m, i + m) || isSolvable(array, m, i + 1) || isSolvable(array, m, i - 1); Is behaving

      • + 2 comments

        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.

        isSolvable(array, m, i + m)
        

        tries to take m steps right.

        isSolvable(array, m, i + 1)
        

        tries to take 1 step right.

        isSolvable(array, m, i - 1)
        

        tries to take 1 step left.

        HackerRank solutions.

        • + 1 comment

          how can i know when the recursive case ended ?

          • + 0 comments

            The 4 lines code with the comment that says "Base cases" corresponds to when the recursive case ends.

            HackerRank solutions.

        • + 0 comments

          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.

    • + 1 comment

      isSolvable(array, m, i - 1) is giving ArrayIndexOutOfBoundsException ...... in the very 1st test case....

      • + 0 comments

        The following lines from my code should prevent that from happening:

        if (i < 0 || array[i] == 1) {
                return false;
        }
        

        since they check for array out of bounds.

        HackerRank solutions.

    • + 1 comment

      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.

      • + 0 comments

        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.

    • + 1 comment

      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

      • + 0 comments

        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.

    • + 0 comments

      _/_

    • + 2 comments
      import java.util.*;
      
      public class Solution {
          public static boolean canWin(int n,int leap, int[] game) {
              int i=0,ptr=0;
                while(i<n){
                  if(i+leap<=n-1 && game[i+leap]==0 && leap!=0) i=i+leap;
                  else if(i+1<=n-1 && game[i+1]==0) i=i+1;
                  else if(i-1>=0 && game[i-1]==0) i=i-1;
                  else return false;
                  game[i]=1;
                  if(i==n-1 || i+leap>=n) return true;
              }
              return true;
          } 
          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+leap];
                  for (int i = 0; i < n; i++) {
                      game[i] = scan.nextInt();
                  }
      
                  System.out.println( (canWin(n,leap, game)) ? "YES" : "NO" );
              }
              scan.close();
          }
      }
      

      This code passes 5 TCs. I've tried it without using recursion.Please help me complete this code.

      • + 3 comments
        [deleted]
        • + 1 comment

          I posted it here because I would like to get the answer from you rshaghoulian

          • + 1 comment

            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.

            • + 1 comment

              I will try it.Thanks a lot.

              • + 1 comment

                Your code fails on the following test case:

                1
                18 4
                0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1
                
                • + 2 comments

                  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.

                  • + 2 comments

                    not your code, the one from Vijay_Ravi...

                    • + 1 comment

                      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

                      if(i+leap<=n-1 && game[i+leap]==0 && leap!=0) i=i+leap;
                                  else if(i+1<=n-1 && game[i+1]==0) i=i+1;
                      

                      which makes jumps of 4,4,4 to

                      if(i+1<=n-1 && game[i+1]==0) i=i+1;
                      else if(i+leap<=n-1 && game[i+leap]==0 && leap!=0) i=i+leap;
                      

                      which makes jumps of 1,1,4,4,4.

                      • + 0 comments

                        Now your code fails on:

                        1
                        16 4
                        0 0 0 1 0 1 0 1 0 1 0 1 0 1 1 1
                        
                  • + 1 comment

                    The change I have made to my code also does jumps of 1,1,4,4,4. Still the 5 testcases fail.

                    • + 0 comments

                      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.

      • + 0 comments

        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).

    • + 1 comment

      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)

      import java.util.*;
      
      public class Solution {
          public static boolean canWin(int leap, int[] game) {
          	
          	
      		for(int i=0, j=0;j<game.length &&i<game.length;j++){
      			if(i+leap>=game.length){
      				return true;
      			}else if(game[i+leap]==0){
      				i=i+leap;
      				if(i<game.length-1 &&i+leap<game.length ){
      					while(game[i]==0 &&i>0 ){
      						i--;
      					}
      					i++;
      
      				}
      
      			}else if(i+1<game.length&&game[i+1]==0){
      				i=i+1;
      
      			}else if(i+1<game.length&&game[i+1]==1){
      				return false;
      			}else{
      				return false;
      			}
      
      
      
      		}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();
      
                  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();
          }
      }
      
      • + 1 comment

        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.

        • + 1 comment

          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 .

          • + 0 comments

            Not sure how many people use this site, maybe 10s of thousands.

    • + 1 comment

      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

      • + 0 comments

        Try the full solution available at HackerRank solutions.

    • + 1 comment

      How can call this function in the main function?

      • + 0 comments

        This code is just a snippet. You can see how I call the function from main in my HackerRank solutions.

    • + 1 comment

      @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.

      • + 0 comments

        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.

    • + 1 comment

      getting eror...

      Solution.java:7: error: illegal start of expression private static boolean solvable(int [] array, int m, int i) {

      • + 0 comments

        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.

    • + 1 comment

      how is this question related to DFS? what is DFS??

      • + 0 comments

        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.

    • + 1 comment

      Hi bro..! I have solved this problem following your solution,but i did'nt get any pts.Tell me please what's the problem???

      • + 0 comments

        You can contact HackerRank about that. Don't worry about points, just try learning the concepts.

        HackerRank solutions.

    • + 1 comment

      sir it not excuting it is showing the errors sir

      • + 1 comment

        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.

        HackerRank solutions.

        • + 1 comment

          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;}

          • + 1 comment

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

                     }
                 }
                 int maxi=-100000;
                 for(int i=0;i<6;i++){
                     for(int j=0;j<6;j++){
                         if(i<=3 && j<=3){
                             int sum=arr[i][j]+arr[i][j+1]+arr[i][j+2]+(arr[i+1][j+1])+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
                             if(sum>maxi) maxi=sum;
                         }
                     }
                 }
                 System.out.println(maxi);
            }
            

            }

            • + 4 comments

              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.

               if(i>=game.length)
                         return true;
              
              if(visited[i]==0)
              {
                  visited[i]=1;
                  if(game[i]==0)
                  {
              
                     if( canWin(game,leap,i+leap))
                         return true;
                     if( canWin(game,leap,i+1))
                     {
              
                         return true;
                     }
                      if(i!=0)
                          if( canWin(game,leap,i-1))
                               return true;
                      }
              }
                  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(); }

                  System.out.println( (canWin(game,leap,0)) ? "YES" : "NO" );
              }
              scan.close();
              

              } }

              • + 1 comment

                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

                • + 0 comments

                  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.

              • + 0 comments

                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.

    • + 0 comments

      This is pure genius, great solution.

    • + 0 comments

      Can You Tell me What we be the recurrence relation for this

    • + 0 comments

      wow that was amazing, I still can't judge where n how to use recursive function

    • + 0 comments

      cann you please explaine in breff

    • + 0 comments

      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?

    • + 0 comments

      hey! amazing solution. i was just wondering, can we use DP to solve this?

    • + 0 comments

      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

    • + 0 comments

      This logic is soo neat. Oh my god.

    • + 0 comments

      could you please explain the logic to move backward i.e why i-1 ?

    • + 1 comment

      This is BRILLIANT. Thankyou!

      • + 0 comments

        pleasure is mine, Happy coding :)

    • + 0 comments

      Why is it false if i < 0 ?

    • + 0 comments

      what a beautifull use of recursion!!!

    • + 0 comments

      good job

    • + 0 comments

      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.

    • + 0 comments

      can you please tell me about your third recursion "isSolveable(leap, game, i-1 ) ".

    • + 0 comments

      // Recursive Cases return isSolvable(leap, game, i + leap) || isSolvable(leap, game, i + 1) || isSolvable(leap, game, i - 1);

                       what's the flow of this?
      
    • + 0 comments

      can anyone explain how this return statement works.

      return isSolvable(leap, game, i + leap) || isSolvable(leap, game, i + 1) || isSolvable(leap, game, i - 1);