Find the Missing IDs - Problem

Given a Customers table with customer IDs and names, find all missing customer IDs within the range from 1 to the maximum customer ID present in the table.

The missing IDs are those that don't exist in the Customers table but fall within the continuous range starting from 1.

Requirements:

  • Find all missing customer IDs in the range [1, max_customer_id]
  • Return results ordered by ID in ascending order
  • Maximum customer_id will not exceed 100

Table Schema

Customers
Column Name Type Description
customer_id PK int Unique customer identifier
customer_name varchar Name of the customer
Primary Key: customer_id
Note: Each row contains a unique customer with their ID and name

Input & Output

Example 1 — Basic Missing IDs
Input Table:
customer_id customer_name
1 Alice
3 Bob
6 Charlie
7 David
Output:
ids
2
4
5
💡 Note:

The maximum customer_id is 7, so we check the range [1, 7]. IDs 1, 3, 6, and 7 exist in the table, so the missing IDs are 2, 4, and 5.

Example 2 — Consecutive IDs
Input Table:
customer_id customer_name
1 Alice
2 Bob
3 Charlie
Output:
ids
💡 Note:

All IDs from 1 to 3 are present consecutively, so there are no missing IDs in the range.

Example 3 — Single Customer
Input Table:
customer_id customer_name
5 Alice
Output:
ids
1
2
3
4
💡 Note:

With only customer_id 5 present, IDs 1, 2, 3, and 4 are missing from the range [1, 5].

Constraints

  • 1 ≤ customer_id ≤ 100
  • customer_name is a non-empty varchar
  • All customer_id values are unique

Visualization

Tap to expand
Find the Missing IDs INPUT Customers Table customer_id name 1 Alice 2 Bob 4 David 5 Eve ID 3 is missing! Expected Range: 1 to 5 1 2 3 4 5 Green = exists, Red = missing ALGORITHM STEPS 1 Find MAX(id) Get highest ID: 5 2 Generate Sequence Create range 1 to MAX 1, 2, 3, 4, 5 3 LEFT JOIN Join sequence with table Sequence 1,2,3,4,5 Customers 1,2,4,5 LEFT JOIN ON id 4 Filter NULL WHERE customer_id IS NULL SELECT seq.id WHERE c.id IS NULL FINAL RESULT Missing IDs ids 3 Gap Found: 1 2 3 4 5 MISSING! OK - 1 missing ID found in range [1, 5] Output: [3] Key Insight: Use a recursive CTE or number generator to create a complete sequence from 1 to MAX(customer_id). Then LEFT JOIN with the Customers table and filter for NULL values to find gaps in the sequence. Time Complexity: O(n) | Space Complexity: O(n) where n = MAX(customer_id) TutorialsPoint - Find the Missing IDs | Optimal Solution
Asked in
Amazon 28 Microsoft 22 Google 18
34.2K Views
Medium Frequency
~12 min Avg. Time
892 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