Interview question
Find each user's longest login streak
Uses the gaps-and-islands pattern to find consecutive login-day streaks after deduplicating same-day activity.
TL;DR
Uses the gaps-and-islands pattern to find consecutive login-day streaks after deduplicating same-day activity.
Gaps and islands, date deduplication, window numbering, grouped streaks, and deterministic tie handling.
Practice the problem like a real interview: restate, reason, implement, and test.
Table: UserLogins(LoginId, UserId, LoggedInAtUtc). Multiple logins on one date count as one active day. Return UserId, streak start, streak end, and day count for the longest streak. If streak lengths tie, return the most recent streak.
A user logs in twice Monday, once Tuesday, and once Thursday. Monday-Tuesday is a two-day streak; Thursday is a one-day streak. Return Monday through Tuesday.
After deduplicating dates, I number each user's days in chronological order. Subtracting that row number from each date creates a constant group key across consecutive dates. I aggregate those islands into streaks, then rank the streaks by length and recency to select one result per user.
WITH LoginDays AS
(
SELECT DISTINCT
l.UserId,
CONVERT(date, l.LoggedInAtUtc) AS LoginDate
FROM dbo.UserLogins AS l
),
NumberedDays AS
(
SELECT
UserId,
LoginDate,
ROW_NUMBER() OVER
(
PARTITION BY UserId
ORDER BY LoginDate
) AS DayNumber
FROM LoginDays
),
Islands AS
(
SELECT
UserId,
LoginDate,
DATEADD(day, -CONVERT(int, DayNumber), LoginDate) AS IslandKey
FROM NumberedDays
),
Streaks AS
(
SELECT
UserId,
MIN(LoginDate) AS StreakStart,
MAX(LoginDate) AS StreakEnd,
COUNT_BIG(*) AS StreakDays
FROM Islands
GROUP BY UserId, IslandKey
),
RankedStreaks AS
(
SELECT
UserId,
StreakStart,
StreakEnd,
StreakDays,
ROW_NUMBER() OVER
(
PARTITION BY UserId
ORDER BY StreakDays DESC, StreakEnd DESC
) AS rn
FROM Streaks
)
SELECT UserId, StreakStart, StreakEnd, StreakDays
FROM RankedStreaks
WHERE rn = 1
ORDER BY UserId;
The query sorts distinct dates per user and then groups the derived islands. An index on (UserId, LoggedInAtUtc) helps the initial read, but converting a huge event history to dates is still substantial work. A maintained daily activity table is often the better source for recurring streak features.
Move to the linked follow-up, next path step, prerequisite, or deeper variant.
Practice the next layer of the same subject.