Search RU
Tasks / SQL / Finding gaps in a sequence
Statement medium

Finding gaps in a sequence

`find_missing_invoices(conn, first_expected=1, last_expected=None)` returns the
invoice numbers missing from the range `[first_expected, last_expected]`.

Table schema:

```sql
CREATE TABLE invoices (
id INTEGER PRIMARY KEY,
invoice_no INTEGER
)
```

Contract:

- return an ascending list of numbers that are absent from the table;
- when `last_expected` is not given, the upper bound is `MAX(invoice_no)`;
- an empty table with no `last_expected` returns `[]`;
- `NULL` in `invoice_no` is ignored: it is neither a number nor a gap;
- duplicate numbers count as one present number;
- if `last_expected < first_expected`, raise `ValueError`;
- both bounds are inclusive: `first_expected` and `last_expected` are checked.

A trailing gap is checked when `last_expected` is greater than the actual
maximum in the table.

**Example:**

```
invoice_no: 1, 2, 4
find_missing_invoices(conn)
→ [3]
```

Write tests for: a gap at the beginning, in the middle, at the end, no gaps,
`NULL`, duplicates, and an empty table.

Python · SQLite
sqlsqlitegapsrecursive-cte
test_solution.py Python 3.14 · SQLite
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

When `last_expected` is not given, where does the checked range end? And is a number missing before the first existing one still a gap?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts