🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Gap & Island Problems — Consecutive Sequences, Missing Data Detection

Advanced SQLProblem Solving⭐ Premium

Gap & Island Problems

Advanced SQL

Find Patterns in Sequences

Gap and island problems ask: "What's missing?" and "What's consecutive?" Islands are consecutive sequences; gaps are the spaces between them. The core technique uses ROW_NUMBER() — consecutive values produce the same difference from the row number.

  • Island Detection — Find consecutive active users, streak days
  • Gap Detection — Find missing dates, gaps in sequences
  • Range Merging — Overlap or adjacency-based grouping
  • Gap Filling — Fill missing dates with interpolated values

This pattern is one of the most common SQL interview questions — it tests whether you can think in sets rather than loops.


The Core Pattern

INPUT: Sparse DatesJan 1 ✓Jan 2 ✓Jan 3 ✓Jan 4 ✗ (missing)Jan 5 ✓Jan 6 ✗ (missing)Jan 7 ✓Jan 8 ✓Jan 9 ✓date - ROW_NUMBER()Consecutive dates produce same result!ROW_NUMBER Computationdate RN date-RNJan 1 1 0Jan 2 2 0Jan 3 3 0 ← same island_idJan 5 4 1 ← different!Jan 7 5 2 ← new islandJan 8 6 2 ← same island_idJan 9 7 2 ← same island_idOUTPUT: IslandsIsland 1: Jan 1 – Jan 33 consecutive daysIsland 2: Jan 51 day (gap: Jan 4, Jan 6)Island 3: Jan 7 – Jan 93 consecutive days

Why the Arithmetic Works

The trick rests on two sequences that advance at the same rate. Consecutive dates increase by exactly one day per row, and ROW_NUMBER() increases by exactly one per row, so subtracting one from the other cancels the shared increment and leaves a constant. When a date is missing, the date keeps stepping while the row number does not, and the difference jumps — which is exactly the boundary between islands.

Rowsale_dateROW_NUMBERdate minus RN
1Jan 110
2Jan 220
3Jan 330
4Jan 541
5Jan 651
6Jan 762

Run the arithmetic on integers rather than dates if the engine resists: casting a date to an integer converts it to days since the epoch, so sale_date::INT - ROW_NUMBER() is plain integer subtraction, and MIN and MAX of the constant recover the island bounds. The same reasoning applies to order numbers, seat numbers, and any sequence that is supposed to be dense.


Classic Gap Problem

-- Find missing dates in a date series
WITH date_range AS (
  SELECT generate_series(
    MIN(sale_date), MAX(sale_date), '1 day'::INTERVAL
  )::DATE AS expected_date
  FROM sales
)
SELECT dr.expected_date AS missing_date
FROM date_range dr
LEFT JOIN sales s ON dr.expected_date = s.sale_date
WHERE s.sale_date IS NULL
ORDER BY dr.expected_date;

Island Detection with ROW_NUMBER

-- Find consecutive days of user activity (streaks)
WITH numbered AS (
  SELECT
    user_id, activity_date,
    activity_date - ROW_NUMBER() OVER (
      PARTITION BY user_id ORDER BY activity_date
    )::INT AS island_id
  FROM user_activity
)
SELECT
  user_id,
  MIN(activity_date) AS streak_start,
  MAX(activity_date) AS streak_end,
  COUNT(*) AS streak_length,
  MAX(activity_date) - MIN(activity_date) + 1 AS days_span
FROM numbered
GROUP BY user_id, island_id
HAVING COUNT(*) >= 3  -- At least 3 consecutive days
ORDER BY user_id, streak_start;

ℹ️

Key Insight: The gap-island pattern uses ROW_NUMBER() to identify consecutive sequences. When you subtract the row number from the value, consecutive values produce the same result, creating "islands." This works for dates, numbers, and any sequential data.


When ROW_NUMBER Breaks: Duplicates and NULLs

Two inputs break the formula. If the same date appears twice — two sales on Jan 2 — the row number still advances by one, so the duplicate lands on a different constant and a single calendar day splits into two islands. Collapse duplicates first with GROUP BY, or accept that you are finding runs of rows rather than runs of days. NULLs are worse: their sort position depends on the engine's NULLS FIRST default, and arithmetic against a NULL yields NULL, which merges unrelated rows into one group.

-- A duplicate day splits into two islands
WITH raw AS (
  SELECT sale_date FROM sales WHERE sale_date = '2024-01-02'
  UNION ALL
  SELECT sale_date FROM sales WHERE sale_date = '2024-01-02'
  UNION ALL
  SELECT sale_date FROM sales WHERE sale_date = '2024-01-03'
)
SELECT sale_date,
       ROW_NUMBER() OVER (ORDER BY sale_date) AS rn,
       sale_date - ROW_NUMBER() OVER (ORDER BY sale_date)::INT AS island_id
FROM raw ORDER BY sale_date;

-- Safe shape: one row per day, NULLs removed
WITH daily AS (
  SELECT DISTINCT sale_date FROM sales WHERE sale_date IS NOT NULL
)
SELECT sale_date - ROW_NUMBER() OVER (ORDER BY sale_date)::INT AS island_id, sale_date
FROM daily ORDER BY sale_date;

De-duplicate before numbering and the pattern becomes deterministic: one row per key in, one island id out, same result on every engine.


Gap Detection in Sequential Data

-- Find gaps in order sequences
WITH numbered_orders AS (
  SELECT
    order_id, order_date,
    LAG(order_date) OVER (ORDER BY order_date) AS prev_date
  FROM orders
)
SELECT
  prev_date AS gap_end,
  order_date AS gap_start,
  order_date - prev_date - 1 AS gap_days
FROM numbered_orders
WHERE order_date - prev_date > 1
ORDER BY prev_date;

Consecutive Value Islands

-- Find consecutive identical values (same revenue for N days)
WITH numbered AS (
  SELECT
    product_id, sale_date, revenue,
    sale_date - ROW_NUMBER() OVER (
      PARTITION BY product_id ORDER BY sale_date
    )::INT AS island_id
  FROM daily_sales
)
SELECT
  product_id,
  MIN(sale_date) AS period_start,
  MAX(sale_date) AS period_end,
  revenue AS daily_revenue,
  COUNT(*) AS consecutive_days,
  SUM(revenue) AS total_revenue
FROM numbered
GROUP BY product_id, island_id, revenue
HAVING COUNT(*) >= 5
ORDER BY product_id, period_start;

Islands Across Business Days

A streak of five trading days is not five calendar days, and naive subtraction counts weekends as gaps. The clean fix is to number against a calendar instead of the raw date: inner join activity to a dense business-day index and run the island arithmetic on that index, so Saturday and Sunday never enter the sequence. The quick fix — subtracting a weekend-aware increment — only holds if you are certain no holiday sits inside the range, which is exactly the assumption that fails in real data.

-- Number against a dense business-day index
WITH trading_days AS (
  SELECT DISTINCT trade_date
  FROM market_events
  WHERE trade_date IS NOT NULL
),
numbered AS (
  SELECT t.trade_date, bd.business_index,
         bd.business_index - ROW_NUMBER() OVER (ORDER BY t.trade_date) AS island_id
  FROM trading_days t
  JOIN business_calendar bd ON bd.cal_date = t.trade_date
)
SELECT MIN(trade_date) AS streak_start,
       MAX(trade_date) AS streak_end,
       COUNT(*) AS trading_days,
       MAX(business_index) - MIN(business_index) + 1 AS calendar_span
FROM numbered
GROUP BY island_id
HAVING COUNT(*) >= 5;

The extra join costs one index lookup per row and removes an entire class of wrong answers: the streak report that quietly disagrees with the trading desk because it counted a long weekend as activity.


Range-Based Islands (Merging Overlapping Ranges)

-- Group overlapping or adjacent bookings
WITH ordered_ranges AS (
  SELECT room_id, start_time, end_time,
    ROW_NUMBER() OVER (PARTITION BY room_id ORDER BY start_time) AS rn
  FROM bookings
),
merged AS (
  SELECT room_id, start_time, end_time,
    start_time AS group_start, end_time AS group_end
  FROM ordered_ranges WHERE rn = 1

  UNION ALL

  SELECT o.room_id, o.start_time, o.end_time,
    CASE WHEN o.start_time <= m.group_end + INTERVAL '30 minutes'
      THEN m.group_start ELSE o.start_time END,
    CASE WHEN o.end_time > m.group_end
      THEN o.end_time ELSE m.group_end END
  FROM merged m
  INNER JOIN ordered_ranges o ON o.room_id = m.room_id
    AND o.rn = (SELECT MIN(rn) FROM ordered_ranges
                WHERE room_id = m.room_id AND rn > m.rn)
)
SELECT room_id, MIN(group_start), MAX(group_end),
  MAX(group_end) - MIN(group_start) AS total_duration
FROM merged GROUP BY room_id;

Missing Consecutive Numbers

-- Find missing seat numbers (like finding empty seats)
WITH numbered AS (
  SELECT seat_number,
    seat_number - ROW_NUMBER() OVER (ORDER BY seat_number) AS gap_id
  FROM occupied_seats
)
SELECT
  MIN(seat_number) + 1 AS gap_start,
  MAX(seat_number) - 1 AS gap_end,
  MAX(seat_number) - MIN(seat_number) - 1 AS gap_size
FROM numbered
GROUP BY gap_id
HAVING MAX(seat_number) - MIN(seat_number) > 1;

Gap Analysis with Statistics

-- Analyze gap patterns per user
WITH gaps AS (
  SELECT user_id, activity_date,
    LAG(activity_date) OVER (PARTITION BY user_id ORDER BY activity_date) AS prev_activity
  FROM user_activity
)
SELECT
  user_id,
  COUNT(*) AS total_gaps,
  AVG(activity_date - prev_activity) AS avg_gap_days,
  MAX(activity_date - prev_activity) AS max_gap_days,
  STDDEV(activity_date - prev_activity) AS stddev_gap_days
FROM gaps
WHERE prev_activity IS NOT NULL AND activity_date - prev_activity > 1
GROUP BY user_id
HAVING COUNT(*) > 5
ORDER BY avg_gap_days DESC;

Filling Gaps Without Blowing Up Memory

Gap filling is the inverse operation, and the risk is the generated series itself. generate_series('2024-01-01', '2024-12-31', '1 day') produces 366 rows and joins in milliseconds; the same expression running ten years per user across a million users produces billions of rows before any aggregate executes. Generate the series at the granularity the report needs, join on a form that matches an index, and push the date bounds into the subquery instead of filtering after the join.

ApproachRows producedBest for
generate_series plus LEFT JOINOne per expected periodFixed calendars, bounded ranges
Recursive CTE spineOne per expected periodEngines without a series function
LAG with a flag and running sumOne per existing rowCounting gaps without materialising them
Window frame with RANGEOne per existing rowForward-filling the last known value

COALESCE(value, 0) is a presentation decision, not a default: zeros are right for a revenue dashboard and wrong for a measurement series, where a missing reading is not a zero.

Picking the Right Variant

Match the variant to the question being asked. Islands find streaks, gaps find missing keys, LAG measures spacing, and range merge resolves overlaps. Each one returns rows even when pointed at the wrong question, which is why this pattern keeps appearing in incident reviews.

QuestionVariantWhat it assumes
Longest run of consecutive daysROW_NUMBER() islandDense input, duplicates removed
Which dates are missingSeries anti-joinA bounded range
How far apart are eventsLAG() differenceA deterministic sort order
Which bookings overlapRecursive merge or a range typeInterval arithmetic you trust
Carry the last value forwardWindow frame or LAG()An ordered index

A standard interview follow-up: what changes when the input is not dense, not sorted, or not unique? Answer with the de-duplication step, the explicit ordering, and the calendar join, and the remainder is bookkeeping.


Quiz: Test Your Knowledge


Follow-Up Questions

  1. How would you find gaps longer than a specific duration?
  2. What's the most efficient way to fill gaps in a time series?
  3. How do you handle gaps across multiple columns simultaneously?
  4. Explain how to detect overlapping ranges and merge them.
  5. How would you implement a sliding window gap detection?

Common Mistakes

Reporting a streak length as COUNT(*) when the source table holds several events on the same day

Fix: Derive the span from MIN and MAX of the date plus one — COUNT(*) is counting events, and the difference shows as soon as a day carries two of them

Numbering rows across the whole table instead of per user, per product or per seat block

Fix: Add PARTITION BY to the ROW_NUMBER call; without it the row number runs through every entity and one streak absorbs the next entity's dates

Using LAG-based gap detection when the output itself must contain the missing dates as rows

Fix: LAG only describes holes between existing rows — materialise the absent dates with a series anti-join whenever the report has to show them with zeros

Key Takeaways

  • Island detection — value - ROW_NUMBER() produces the same result for consecutive values
  • Gap detection — LAG() + difference check identifies missing values
  • Range merging — Recursive CTE for overlapping/adjacent range consolidation
  • Gap filling — generate_series + LEFT JOIN to fill missing dates
  • HAVING COUNT(*) >= N — Filter islands by minimum consecutive length
  • Works for dates AND numbers — The ROW_NUMBER trick is universal for sequential data
🔒

Premium Content

Gap & Island Problems — Consecutive Sequences, Missing Data Detection

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
💼Interview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement