7

I was working on a Codility problem:

You are given two non-empty zero-indexed arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river.

The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q. Initially, each fish has a unique position.

Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where:

0 represents a fish flowing upstream, 1 represents a fish flowing downstream. If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them. After they meet:

If A[P] > A[Q] then P eats Q, and P will still be flowing downstream, If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream. We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive.

**Complexity:**

expected worst-case time complexity is O(N); expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Here is my solution: (100% correct results)

public int solution(int[] a, int[] b) {
  int remFish = a.length; 
  int i = 0; 
  for (i = 0; i < b.length; i++) {
    if(b[i] != 0){
      /*remFish++; }else { */ break; 
    }
  } 
  Stack<Integer> myQ = new Stack<Integer>(); 
  for (int j = i; j < b.length; j++) { 
    if(b[j] == 1)
    {
      myQ.add(j); 
    } 
    while(b[j] == 0 && !myQ.isEmpty()) {
      if(a[j] > a[myQ.peek()]){ 
        myQ.pop(); remFish--; 
      }else{ 
        remFish--; 
      break; 
      }
    } 
  } 
  return remFish;
}

Could someone help me understand whether my solution passes the complexity requirements?

Prune
  • 76,765
  • 14
  • 60
  • 81
Nicky
  • 1,025
  • 3
  • 15
  • 29

5 Answers5

6

Your Idea was good. I tried to make it more understandable.

import java.util.*;

class Solution {
    public int solution(int[] A, int[] B) {

        int numFishes = A.length;

        // no fishes
        if(numFishes == 0)
            return 0;

        // Deque stores the fishes swimming downstreams (B[i]==1) 
        Deque<Integer> downstreams = new ArrayDeque<Integer>();

        for(int i = 0; i < A.length; i++){

            //Fish is going downstreams
            if(B[i] == 1){
                // push the fish into the Deque
                downstreams.push(A[i]); 
            }//Fish is going upstreams
            else{
                while( !downstreams.isEmpty() ){ 
                    // Downstream-fish is bigger 
                    if( downstreams.peek() > A[i] ){
                        //Upstream-fish gets eaten
                        numFishes--;
                        break;    
                    }// Downstream-fish is smaller
                    else if(downstreams.peek() < A[i]){
                        //Downstream-fish gets eaten
                        numFishes--;
                        downstreams.pop();
                    }
                }
            }  
        }    

        return numFishes;
    }
}
F.Schmid
  • 76
  • 1
  • 5
0

It's hard to follow this code with the strange data structures and lack of variable names, but I think I have the needed understanding ...

Space complexity: The only dimensioned space you have is myQ, which is bounded by the total quantity of fish. Thus, this is O(n).

Time Complexity: Given your strange logic, this was harder to follow. The paired decrements of remFish and the abuse of while -- break confused me for a couple of minutes. However, the simpler analysis is ...

The while -- break turns that loop into a simple if statement, since you always break the loop on first iteration. Therefore, your only true iteration is the for loop, bounded by the quantity of fish. Thus, this is also O(n).

Among other properties, note that you decrement numFish on each iteration, and it never drops as far as 0.


Why do you gauge one iteration on a.length and another on b.length? Those must be the same, the starting quantity of fish.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • This is wrong, he does not break the while loop on the first iteration, and while loop is not turned into a simple if statement. – noviewpoint Feb 17 '22 at 17:50
  • Right; I see my error now, stemming from the original formatting. Thanks for the correction. – Prune Feb 18 '22 at 19:36
0

N fish get a series of O(1) checks. That's O(n).

The O(n) fish swimming downstream get added to myQ which is also O(1) each for another O(n) term.

Every iteration of the inner loop kills a fish in O(1) time. At most O(n) fish die so that is also O(n).

Adding it all up, the total is O(n).

btilly
  • 43,296
  • 3
  • 59
  • 88
0

I got 100/100 with this code. I've seen other solutions more concise. But this one is pretty readable.

ArrayDeque<Integer> downstreams = new ArrayDeque<>();
    int alive = 0;
    for (int i = 0; i < A.length; i++) {
        int currFish = A[i] * (B[i] == 1 ? -1 : 1);
        if (currFish < 0) {
            downstreams.push(currFish);
            alive++;
        } else {
            Iterator it = downstreams.iterator();
            boolean eaten = false;
            while (it.hasNext()) {
                int down = (int) it.next();
                if (Math.abs(currFish) > Math.abs(down)) {
                    it.remove();
                    alive--;
                    eaten = false;
                } else {
                    eaten = true;
                    break;
                }
            }
            if (!eaten) {
                alive++;
            }
        }
    }
    return alive;
0

Here is python3 try with time complexity O(N)

def fish_eater(fish_size, direction):
    stack = []
    fish_alive = len(fish_size)
    if not len(fish_size):
        return 0
    for i in range(len(fish_size)):
        if direction[i] == 1:
            stack.append(fish_size[i])
        else:
            while len(stack):
                if stack[-1] > fish_size[i]:
                    fish_alive -= 1
                    break
                if stack[-1] < fish_size[i]:
                    fish_alive -= 1
                    stack.pop()
    return fish_alive

Useful resource about time complexity and big O notation understanding-time-complexity-with-python

Ahmed Shehab
  • 1,657
  • 15
  • 24