The turn in the tape
- O(log n) · Easy
- Free
- Python
- JavaScript
- lists
- search
- comparisons
Problem
Owen clocks in for the night shift and finds on the floor the tape that prints the part codes. The tape prints them from smallest to largest, but someone cut the roll at one point and taped the beginning onto the end: now the list starts halfway through, climbs up to the biggest code and starts over from the smallest one.
Write a function that takes the list of codes and returns the position of the smallest code, counting from 0. With 40, 52, 60, 7, 14, 22 and 31 you return 3, because the 7 ended up at position 3. If nobody cut the roll, the smallest one is still at the front and you return 0.
The codes are all different and the tape never arrives empty. Them being different matters: with two equal codes at the edges there would be no way to tell which side the cut ended up on.
You cannot look for the smallest one with what the language already gives you (min, Math.min, index, indexOf): the whole point of the challenge is not to read the whole tape.
Idea: at every step you are left with a stretch of the tape. Compare the code in the middle of that stretch with the code that same stretch ends on, not with the last one of the whole tape. If the middle one is bigger, the cut ended up to its right and you never look at the left half again. If not, the smallest one is the middle one or it is before it.
Examples
The roll somebody cut
[40, 52, 60, 7, 14, 22, 31] → 3
Nobody cut the roll
[7, 14, 22, 31, 40, 52, 60] → 0
Cut right after the first one
[9, 1, 3, 5, 7] → 1
Cut right before the last one
[2, 3, 4, 5, 1] → 4
Two codes
[8, 4] → 1
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def turn_point(codes):
passJavaScript
function turnPoint(codes) {
}It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.