📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the gaps-and-islands problem, and how do you solve it with window functions?

Mid-Level Sql Intermediate

🎯 Key points

  • Islands: value minus ROW_NUMBER gives a constant group key
  • GROUP BY that key for island start and end
  • Gaps: LEAD to find jumps larger than one step
  • Deduplicate values first
  • Single pass instead of self-joins

⏱ 30-second answer

Islands are runs of consecutive values (consecutive login days, contiguous ids); gaps are the missing values between them. Classic solution: subtract ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY LoginDate) days from each date; rows in the same island share the same result, so GROUP BY UserId, grp gives start and end with MIN/MAX. For gaps, use LEAD(value) OVER (ORDER BY value) and keep rows where the next value is more than one step away. Both are single-pass and need distinct values first.

🔍 What the interviewer is checking

Checks advanced set-based thinking on sequences such as consecutive days or ranges.

↩ Usually asked after

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me