Find the Missing IDs - Problem

🔍 Find the Missing Customer IDs

You work as a data analyst for an e-commerce company, and you've discovered that some customer IDs are missing from your database! This could indicate data corruption or system errors that need immediate attention.

Given a Customers table with customer IDs and names, your task is to identify all the missing customer IDs in the range from 1 to the maximum customer_id present in the table.

📊 Table Structure:

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| customer_id | int |
| customer_name | varchar |
+---------------+---------+

Key Points:

  • 🔑 customer_id is unique for each customer
  • 📈 Maximum customer_id will not exceed 100
  • 🎯 Find IDs missing in range [1, max_customer_id]
  • 📋 Return results ordered by missing IDs in ascending order

Think of it like finding missing pages in a numbered book - if you have pages 1, 3, 5, 7, you need to identify that pages 2, 4, and 6 are missing!

Input & Output

example_1.sql — Basic Missing IDs
$ Input: Customers table: +-------------+---------------+ | customer_id | customer_name | +-------------+---------------+ | 1 | Alice | | 3 | Bob | | 7 | Charlie | | 9 | David | | 10 | Eve | +-------------+---------------+
Output: +-----+ | ids | +-----+ | 2 | | 4 | | 5 | | 6 | | 8 | +-----+
💡 Note: The maximum customer_id is 10, so we need to check range [1,10]. Customer IDs 1,3,7,9,10 exist, so missing IDs are 2,4,5,6,8.
example_2.sql — Consecutive IDs
$ Input: Customers table: +-------------+---------------+ | customer_id | customer_name | +-------------+---------------+ | 1 | John | | 2 | Jane | | 3 | Jack | +-------------+---------------+
Output: Empty result set (no missing IDs)
💡 Note: All IDs from 1 to 3 are present consecutively, so there are no missing customer IDs in the range.
example_3.sql — Single Customer
$ Input: Customers table: +-------------+---------------+ | customer_id | customer_name | +-------------+---------------+ | 5 | Solo | +-------------+---------------+
Output: +-----+ | ids | +-----+ | 1 | | 2 | | 3 | | 4 | +-----+
💡 Note: Only customer_id 5 exists, so IDs 1,2,3,4 are missing in the range [1,5].

Time & Space Complexity

Time Complexity
⏱️
O(n)

Database optimizes set operations with hash-based algorithms

n
2n
Linear Growth
Space Complexity
O(n)

Temporary space for generated range and hash tables

n
2n
Linearithmic Space

Constraints

  • 1 ≤ customer_id ≤ 100
  • customer_id values are unique
  • customer_name is a non-empty varchar
  • The table contains at least 1 customer
  • Results must be ordered by ids in ascending order
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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