The catches of the same weight
- O(log n) · Easy
- Free
- Python
- JavaScript
- lists
- search
- indexes
Problem
Nora skippers a fishing boat, and when she gets to the market she hands in the log of the day: one row per catch, with its weight in kilos, already sorted from the lightest to the heaviest. A buyer names a weight and wants to know from which row to which row the catches of that weight are, so he can take them all at once.
Write a function that takes the list of weights sorted from smallest to largest and a weight, and returns a list of two numbers: the row where that weight shows up for the first time and the row where it shows up for the last time. Rows are counted from 0, so in 2, 4, 4, 4, 7 and 9 the weight 4 returns [1, 3].
If that weight never came up all day, you return [-1, -1]. With an empty log it is the same.
The log always arrives sorted: you do not have to check it.
You cannot use what the language already gives you to find a position (index, indexOf, lastIndexOf) or to count repeats (count): the whole point of the challenge is to split the log.
Idea: it is two searches by halves over the same list. In both of them, when the middle row holds the weight you are after, write it down and do not stop: one keeps going to the left, to see if there is another one before it, and the other one goes to the right.
Examples
The four-kilo catch
[2, 4, 4, 4, 7, 9], 4 → [1, 3]
A single row
[2, 4, 4, 4, 7, 9], 9 → [5, 5]
The first row
[2, 4, 4, 4, 7, 9], 2 → [0, 0]
That weight never came up
[2, 4, 4, 4, 7, 9], 5 → [-1, -1]
The whole log at the same weight
[5, 5, 5, 5], 5 → [0, 3]
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def span(weights, weight):
passJavaScript
function span(weights, weight) {
}It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.