1472. Gap in the Progression
A shelf of numbered crates once held an evenly spaced run of values: each crate was a fixed positive step d above the previous one, so the original run was a strictly increasing arithmetic progression. One crate from the middle of the run was lost, but the first and the last crate are still there.
The remaining values are given in nums, in increasing order. Return the value of the lost crate. The step is not given, but it can be recovered from the ends: d = (last - first) / nums.length.
Before the lost term, nums[i] == nums[0] + i*d holds; from the lost term onward it fails, so a binary search can find the first index where it breaks. Aim for O(log n) time and O(1) extra space.
Example 1
- Input:
- nums = [3,7,11,19,23]
- Output:
- 15
- Explanation:
The step is (23 - 3) / 5 = 4, and the sequence 3, 7, 11, 15, 19, 23 lacks only 15.
Example 2
- Input:
- nums = [-10,-6,-2,2,10,14]
- Output:
- 6
- Explanation:
The step is (14 - (-10)) / 6 = 4, and the gap sits between 2 and 10, so the missing value is 6.
Constraints
3 ≤ nums.length ≤ 1000
-109 ≤ nums[i] ≤ 109
step d ≥ 1
exactly one interior term (never the first or last) is missing
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(log n)
- Space
- O(1)