The store on a streak
- O(2ⁿ) · Legendary
- Full plan
- SQL
- window functions
- dates
Problem
The owner swears orders come in streaks: a few days in a row something comes in, and then the store goes quiet. The owner wants to see them. A streak is a run of calendar days in a row with at least one order; a day with none breaks it, and a day on its own is a streak of 1.
For each streak, show its first day, its last day, and how many days it lasts, in that order. The one from January 9 to 12 lasts 4, and it makes no difference that two orders came in on the 12th: it's a single day.
The longest streak goes on top; between two of the same length, the earlier one goes first. Dates count the way they're written down: the order dated the 20th still hasn't been fixed, and that day is a streak all by itself.
What it has to return
These rows, in this order
| first_day | last_day | days |
|---|---|---|
| 2026-01-09 | 2026-01-12 | 4 |
| 2026-01-03 | 2026-01-04 | 2 |
| 2026-01-14 | 2026-01-15 | 2 |
| 2026-01-20 | 2026-01-20 | 1 |
This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.
You start with this
SQL
SELECT DISTINCT placed
FROM orders
ORDER BY placedIt opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.
More O(2ⁿ) challenges
- The Winters oneSQL · recursion · strings · window functions
- Their people's peopleSQL · recursion · grouping
- Use it or lose itSQL · recursion · strings
- Can I borrow your notes?SQL · subqueries · joins · grouping
- Frank against everyoneSQL · recursion · joins
- Not one more, not one lessSQL · window functions · operations