Missing Number In Arithmetic Progression - Problem

In some array arr, the values were in arithmetic progression: the differences arr[i + 1] - arr[i] are all equal for every 0 <= i < arr.length - 1.

A value from arr was removed that was not the first or last value in the array.

Given the modified array arr, return the removed value.

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,3,7,9]
Output: 5
💡 Note: The original arithmetic progression was [1,3,5,7,9] with common difference 2. The number 5 was removed, so we return 5.
Example 2 — Negative Numbers
$ Input: arr = [15,13,9]
Output: 11
💡 Note: The original sequence was [15,13,11,9] with common difference -2. The missing number is 11.
Example 3 — Larger Difference
$ Input: arr = [5,7,11,13]
Output: 9
💡 Note: The original sequence was [5,7,9,11,13] with common difference 2. The number 9 was removed.

Constraints

  • 3 ≤ arr.length ≤ 1000
  • -105 ≤ arr[i] ≤ 105
  • The given array represents a valid arithmetic progression with one missing element

Visualization

Tap to expand
Missing Number In Arithmetic Progression INPUT Modified Array (missing element) 1 3 7 9 [0] [1] [2] [3] Original AP sequence: 1, 3, ?, 7, 9 Input Details arr = [1, 3, 7, 9] Length: 4 First: 1, Last: 9 ALGORITHM STEPS 1 Calculate Expected Diff diff = (last - first) / n = (9-1)/4 = 2 2 Binary Search Setup left=0, right=3 Find where gap breaks 3 Check Mid Position mid = 1, arr[1] = 3 Expected: 1 + 1*2 = 3 OK Move left = mid + 1 4 Find Missing Value mid = 2, arr[2] = 7 Expected: 1 + 2*2 = 5 7 != 5 (Missing found!) Time: O(log n) | Space: O(1) FINAL RESULT Complete AP Sequence: 1 3 5 7 MISSING Output 5 Verification 3 - 1 = 2 OK 5 - 3 = 2 OK 7 - 5 = 2 OK Key Insight: In a valid AP, each element at index i should equal: first + i * common_diff. Using Binary Search, find where arr[mid] != expected value. The missing number is the expected value. Common diff = (last - first) / array_length since one element is missing from original AP. TutorialsPoint - Missing Number In Arithmetic Progression | Binary Search Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen