Finding gaps in sequences in SQL - Time & Space Complexity
When we look for missing numbers in a sequence stored in a database, we want to know how the time to find these gaps changes as the sequence grows.
We ask: How does the work increase when the list of numbers gets bigger?
Analyze the time complexity of the following code snippet.
WITH Numbered AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS rn
FROM sequence_table
)
SELECT id + 1 AS gap_start
FROM Numbered
WHERE id + 1 <> (SELECT id FROM Numbered WHERE rn = Numbered.rn + 1)
;
This code finds gaps in a sequence by comparing each number with the next expected number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each row in the sequence to compare with the next row.
- How many times: Once for each row in the sequence.
As the number of rows grows, the database checks each row once to find gaps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 comparisons |
| 100 | About 100 comparisons |
| 1000 | About 1000 comparisons |
Pattern observation: The work grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to find gaps grows linearly as the sequence gets longer.
[X] Wrong: "Finding gaps requires checking every possible number between the smallest and largest, so it must be much slower than just scanning the sequence."
[OK] Correct: The query only looks at existing rows once, comparing neighbors, so it does not check every missing number individually.
Understanding how to find gaps efficiently shows you can work with sequences and spot missing data quickly, a useful skill in many data tasks.
"What if we changed the query to find gaps in an unsorted sequence without using ROW_NUMBER()? How would the time complexity change?"
Practice
LEAD() function when finding gaps in a sequence of numbers in SQL?Solution
Step 1: Understand the role of LEAD()
TheLEAD()function allows you to look at the next row's value in the current row's context.Step 2: Identify how LEAD() helps find gaps
By comparing the current number with the next number, you can detect if there is a gap (difference greater than 1).Final Answer:
To compare each number with the next number in the sequence -> Option BQuick Check:
LEAD() compares current and next values [OK]
- Thinking LEAD() sums values
- Confusing LEAD() with aggregate functions
- Using LEAD() to sort data
LEAD() to find gaps in a sequence column named num in table numbers?Solution
Step 1: Check LEAD() syntax
The correct syntax requiresLEAD(column) OVER (ORDER BY column)to define the order for the window function.Step 2: Identify the correct option
SELECT num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers; usesLEAD(num) OVER (ORDER BY num), which is the correct form to get the next number in order.Final Answer:
SELECT num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers; -> Option CQuick Check:
LEAD() needs OVER with ORDER BY [OK]
- Omitting OVER clause
- Not specifying ORDER BY inside OVER
- Using LEAD() without alias
numbers with column num containing values (1, 2, 4, 5, 7), what will the following query return?SELECT num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers;
Solution
Step 1: Understand LEAD() output
LEAD(num) returns the next row'snumvalue ordered bynum. So each row shows its ownnumand the next number.Step 2: Apply to given data
For values 1,2,4,5,7:
1's next is 2
2's next is 4
4's next is 5
5's next is 7
7 has no next, so nullFinal Answer:
[{num:1, next_num:2}, {num:2, next_num:4}, {num:4, next_num:5}, {num:5, next_num:7}, {num:7, next_num:null}] -> Option AQuick Check:
LEAD() shifts values down by one [OK]
- Assuming LEAD() repeats current value
- Expecting gaps filled automatically
- Confusing LEAD() with LAG()
num sequence but returns no rows:SELECT num FROM numbers WHERE LEAD(num) OVER (ORDER BY num) - num > 1;
What is the error?
Solution
Step 1: Understand window function restrictions
Window functions like LEAD() cannot be used directly in the WHERE clause because WHERE filters rows before window functions are applied.Step 2: Correct approach
Use a subquery or CTE to compute LEAD() first, then filter in an outer query.Final Answer:
You cannot use window functions directly in WHERE clause -> Option AQuick Check:
Window functions not allowed in WHERE [OK]
- Trying to filter window function in WHERE
- Missing OVER clause
- Expecting LEAD() to work like aggregate
orders with an integer column order_id that should be sequential but may have missing numbers. Which query correctly finds all missing order_id values between the minimum and maximum present?Solution
Step 1: Generate full sequence range
Usegenerate_seriesfrom minimum to maximumorder_idto create all possible IDs.Step 2: Find missing IDs by left join
Left join this sequence to existing orders and select IDs where no matching order exists (NULL in orders).Final Answer:
WITH seq AS (SELECT generate_series(MIN(order_id), MAX(order_id)) AS id FROM orders) SELECT id FROM seq LEFT JOIN orders ON seq.id = orders.order_id WHERE orders.order_id IS NULL; -> Option DQuick Check:
Generate full range, then find missing with LEFT JOIN [OK]
- Using LEAD() alone misses multiple gaps
- Incorrect NOT IN subquery logic
- Assuming order_id + 1 always missing
Ready to prove it?
Pass the test and this pattern moves unknown
