The signal that comes back
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- lists
- indexes
- loops
Problem
Up at the Mount Vela station, the radio telescope logs one signal an hour, as a whole-number code, in the order they arrive. The astronomers are looking for the code that came back after the longest time.
Write a function that takes the list of codes (whole numbers, possibly empty) and returns, as a whole number, the largest gap between two entries with the same code: the position of the later one minus the position of the earlier one. If a code shows up three or more times, you measure from its first time to its last. An entry never pairs with itself: if no code repeats, or the list is empty, you return 0.
With [7, 3, 9, 3, 7, 5, 3]: the 7 is at positions 0 and 4, a gap of 4. The 3 is at 1, 3 and 6, and from 1 to 6 is 5. You return 5.
Examples
The example
[7, 3, 9, 3, 7, 5, 3] → 5
Two in a row
[4, 4] → 1
Nothing repeats
[1, 2, 3] → 0
Three appearances
[8, 1, 2, 8, 3, 8] → 5
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def longest_return(codes):
passJavaScript
function longestReturn(codes) {
}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.