Tide gauge zigzag
EasyOnline Assessment
Check that a tide gauge is really oscillating the way a healthy float should.
A healthy gauge alternates: it rises, then falls, then rises, and so on. Take each pair of adjacent readings and look at the step between them:
- If the two readings differ by
toleranceor less (in either direction), the step is flat and is ignored completely; it neither counts as a rise or a fall nor breaks anything. - Otherwise the step is a rise (the later reading is higher) or a fall (it is lower).
Considering only the rises and falls, in order, they must strictly alternate. A flat step does not reset anything: after a rise, a flat step, then another rise, the gauge has risen twice in a row. The very first rise or fall may be of either kind.
Input: readings, a list of integers, and tolerance, a non-negative integer.
Output: the index of the first reading that ends a step of the same kind as the previous non-flat step (the later reading of the offending pair), or -1 if the readings alternate correctly throughout.
Example 1
- Input:
- [[3,9,4,8,8,2],1]
- Output:
- -1
- Explanation
- With tolerance 1 the steps are +6, -5, +4, 0, -6. The 0 step is flat and ignored, so the non-flat steps are rise, fall, rise, fall, which alternate: -1.
Example 2
- Input:
- [[6,6,6,2,9,9,12],1]
- Output:
- 6
- Explanation
- The steps are 0, 0, -4, +7, 0, +3. The flat steps are ignored, leaving fall, rise, rise. The second rise ends at index 6, since the flat step between the two rises does not break the pair.
Example 3
- Input:
- [[0,5,2,6,9],3]
- Output:
- 3
- Explanation
- With tolerance 3 the steps are +5, -3, +4, +3. A change of exactly 3 is flat, so only +5 and +4 count and both are rises. The offending step ends at index 3.
Constraints
0 <= readings.length <= 5,000-100,000 <= readings[i] <= 100,0000 <= tolerance <= 100,000