The penguin line
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- conditionals
- loops
- lists
Problem
At feeding time, the penguins at the rescue center line up in front of Thandiwe Mokoena, their keeper, and her bucket of fish. She is watching one who is recovering from a fracture, and wants to know how many fish she will have handed out in total when that penguin finishes eating.
You get fish, a list of whole numbers greater than 0 with at least one element: how many fish each penguin wants, in line order. And k, the position of the penguin she is watching, counting from 0 (always valid). On each turn, the penguin at the front gets one fish. If it still wants more, it goes to the back of the line; if it has had all it wanted, it goes off to swim.
Return how many fish have been handed out at the moment penguin k gets its last one, counting that one.
With [2, 3, 1] and k 1 (the one that wants 3), the turns are: 0, 1, 2 (leaves), 0 (leaves), 1, 1 (leaves). The watched penguin finishes with the sixth fish: you return 6.
Examples
The example
[2, 3, 1], 1 → 6
A single penguin
[4], 0 → 4
Everyone wants one
[1, 1, 1, 1], 2 → 3
Everyone wants the same
[3, 3, 3], 1 → 8
The watched one is first
[5, 1, 2], 0 → 8
The watched one is last
[2, 5, 1, 4], 3 → 11
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def fish_until(fish, k):
passJavaScript
function fishUntil(fish, k) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.