The stuck sensor
- O(n) · Medium
- Full plan
- Python
- JavaScript
- lists
- loops
Problem
In the lab, a healthy sensor changes its reading almost every second. When it gets stuck, it repeats the same one several times in a row, and the technician wants to know which value it stayed stuck on the longest. Write a function that takes the list of readings (whole numbers, which can be negative; the list is never empty) and returns the value of the longest run of equal readings in a row. Return the value, not how long it lasted. With [4, 7, 7, 7, 2, 2, 7] the longest run is the three 7s: you return 7. Only readings in a row count: in [3, 8, 3, 8, 3, 6, 6] the 3 shows up three times, but never two together, and 6 wins.
If two runs tie in length, the one that came first wins. If no reading repeats, every run has length 1: return the first reading.
Examples
The example
[4, 7, 7, 7, 2, 2, 7] → 7
Most frequent is not longest in a row
[3, 8, 3, 8, 3, 6, 6, 3] → 6
A single reading
[9] → 9
None repeats
[4, 1, 8] → 4
A tie, the first one wins
[2, 2, 5, 5] → 2
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def stuck_value(readings):
passJavaScript
function stuckValue(readings) {
}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.