Sort by

recency

|

3268 Discussions

|

  • + 0 comments

    python implementation

    def jumpingOnClouds(c):
        # Write your code here
        jumps = 0
        i=0
        c_len=len(c)
        while i < c_len - 1:
            j=2
            while j >0:
                if i+j<=c_len-1:
                    if c[i+j]==0:
                        i+=j
                        jumps+=1
                        break
                    else:
                        j-=1
                else:
                    j-=1
        return jumps
    
  • + 0 comments
    public static int jumpingOnClouds(List<Integer> c) {
    // Write your code here
    

    int jumps = 0; int i = 0;

    while (i < c.size() - 1) {
        // Prefer jumping 2 steps if possible, otherwise jump 1 step
        if (i + 2 < c.size() && c.get(i + 2) == 0) {
            i += 2;
        } else {
            i += 1;
        }
        jumps++; // Count the jump
    }
    
    return jumps;
    }
    
  • + 0 comments

    Python 3

    def jumpingOnClouds(c):

    jump = 0
    i = 0
    while True:
        if (i+2)<= (len(c)-1) and c[i+2] == 0 :
            jump = jump + 1
            i = i + 2
    
        elif (i+1)<= len(c)-1:
            i = i + 1
            jump = jump + 1
    
        else:
            break
    
    return jump
    
  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/GNof9B-9CN0

    int jumpingOnClouds(vector<int> c) {
        int result = 0, index = 0;
        while(index < c.size() - 1){
            if(c[index + 2] == 1) index++;
            else index+=2;
            result++;
        }
        return result;
    }
    
  • + 0 comments

    Python

    This solutions separates constants and variables, allowing for faster execution. The max_index and size are constants, allowing us to only measure the length of the array once. For the solution to be optimal, we need to try to jump the furthest we can. Since the question emphasizes that there's always a possible solution, this means that in case there's a dangerous cloud in position + 2 we can always jump to position + 1 and this will be the minimum number of jumps.

    def jumpingOnClouds(clouds: list[int])-> int:
        position: int = 0
        jumps: int = 0
        size: int = len(clouds)
        max_index: int = size -1
        
        while position < max_index:
            if(
                position + 2 > max_index or
                clouds[position + 2] == 1
            ):
                position += 1
            else:
                position += 2
            jumps += 1
        
        return jumps