DEV Community

Déborah Mesquita
Déborah Mesquita

Posted on

Solution to Fish task by codility

This task is a training on how to use stacks

The two main important things to notice so you can complete the task are:

  1. A fish going upstream will NEVER meet a downstream fish that comes next
  2. A upstream fish can ether eat all the downstream fish or die

This is a possible solution using one stack:

def solution(A,B):
    alive = len(A)
    downstream = []
    for size,direction in zip(A,B):
        if direction == 1:
            while downstream:
                if size < downstream[-1]:
                    # upstream fish is eaten
                    alive = alive - 1
                    # upstream fish eats the other one
                    alive = alive - 1
    return alive
Enter fullscreen mode Exit fullscreen mode

Top comments (0)