Longest Consecutive Full-Attendance Day Streak
Easy · Data Manipulation (SQL/Python) · Data Engineer · Technical Screen
Problem Statement
Given a fixed company roster and daily check-in logs, determine the length of the longest unbroken chain of adjacent calendar dates on which 100% of the workforce checked in as present.
In Python, implement:
def longest_streak(employees: List[int], daily_attendance: List[List[str]]) -> int:
employeeslists the distinct integer IDs of every staff member on the roster.daily_attendanceis a list of[employee_id, attendance_date, status]rows, whereemployee_idis an integer fromemployees,attendance_dateis an ISO calendar string'YYYY-MM-DD', andstatusis'Y'(present) or'N'(absent), with at most one row per(employee_id, attendance_date)pair.
In the equivalent PostgreSQL schema, employees(employee_id INTEGER PRIMARY KEY) holds the staff roster and daily_attendance(employee_id INTEGER, attendance_date DATE, status TEXT, PRIMARY KEY (employee_id, attendance_date)) stores non-null check-in records referencing employees, with a read-only query returning one row and one integer column named longest_streak.
Apply the following attendance and streak rules:
- A calendar date qualifies only when every employee in
employeeshas a row withstatus = 'Y'on that date. - If an employee has
status = 'N'or has no row recorded on that date, the employee is not confirmed present and that date fails to qualify. - An unrecorded calendar day (zero rows in
daily_attendance) never qualifies and breaks any streak between surrounding dates. - Streak adjacency follows real Gregorian calendar dates (
+1day), continuing seamlessly across weekends, month-ends, year-ends, and leap days. - Return
0whendaily_attendanceis empty or when zero dates achieve full attendance.
Examples
Example 1
Input:
employees = [10, 20, 30]
daily_attendance = [
[10, '2025-03-30', 'Y'], [20, '2025-03-30', 'Y'], [30, '2025-03-30', 'Y'],
[10, '2025-03-31', 'Y'], [20, '2025-03-31', 'Y'], [30, '2025-03-31', 'Y'],
[10, '2025-04-01', 'Y'], [20, '2025-04-01', 'Y'], [30, '2025-04-01', 'Y'],
[10, '2025-04-02', 'Y'], [20, '2025-04-02', 'N'], [30, '2025-04-02', 'Y'],
[10, '2025-04-03', 'Y'], [20, '2025-04-03', 'Y'], [30, '2025-04-03', 'Y']
]
Output: 3
Walk-through: All three staff members (10, 20, 30) check in 'Y' on March 30, March 31, and April 1, forming a 3-day run across the March-to-April boundary. Employee 20 logs 'N' on April 2, resetting the run; April 3 forms a separate 1-day run, so the longest run is 3.
Example 2
Input:
employees = [4, 8]
daily_attendance = [
[4, '2025-06-10', 'Y'], [8, '2025-06-10', 'Y'],
[4, '2025-06-11', 'Y'],
[4, '2025-06-12', 'Y'], [8, '2025-06-12', 'Y'],
[4, '2025-06-13', 'Y'], [8, '2025-06-13', 'Y'],
[4, '2025-06-15', 'Y'], [8, '2025-06-15', 'Y']
]
Output: 2
Walk-through: June 10 qualifies (1-day run), but June 11 fails because employee 8 has no entry at all—even though every recorded row on June 11 is 'Y'. June 12 and June 13 both have full attendance (2-day run). June 14 has zero records and creates a calendar gap before June 15 (1-day run), leaving 2 as the maximum.
Constraints
employeescontains at least1unique integer ID and stays fixed across all dates.daily_attendancemay contain0or more rows in arbitrary order, with at most one row per(employee_id, attendance_date).- Every
attendance_dateis a valid'YYYY-MM-DD'Gregorian calendar date, and everystatusis'Y'or'N'. - Do not assume full attendance on a date just because zero
'N'records appear on that date; every member ofemployeesmust have an explicit'Y'record.
Step-by-step walkthrough
Understand the problem and rules
We want the length of the longest unbroken streak of adjacent calendar days on which 100% of the workforce checked in present (
'Y'). When zero dates achieve full attendance, we return0.In the SQL schema we have
employees(employee_id)anddaily_attendance(employee_id, attendance_date, status). In the Python judge, those same two inputs arrive as: -employees: a list of staff IDs such as[4, 8]. -daily_attendance: a list of[employee_id, attendance_date, status]rows, whereattendance_dateis an ISO date string ('YYYY-MM-DD', such as'2025-06-11') andstatusis'Y'or'N'.Three rules are worth pinning down immediately:
Employees = {4, 8} (need 2 'Y' records on a date for it to qualify) Calendar day Rows recorded Qualifies? Why 2025-06-10 (4, 'Y'), (8, 'Y') Yes 2 of 2 present -> streak = 1 2025-06-11 (4, 'Y') [employee 8 missing] No Missing row = not present! 2025-06-12 (4, 'Y'), (8, 'Y') Yes Starts a fresh streak = 1 2025-06-13 (4, 'Y'), (8, 'Y') Yes 2 of 2 present -> streak = 2 2025-06-14 [no rows recorded at all] No Unrecorded date = calendar gap! 2025-06-15 (4, 'Y'), (8, 'Y') Yes Starts a fresh streak = 1Weekends, month boundaries (
Mar 31 -> Apr 1), year boundaries (Dec 31 -> Jan 1), and leap days (2024-02-28 -> 2024-02-29 -> 2024-03-01) are ordinary consecutive calendar days.Why scanning every day on the calendar is wasteful
A literal brute-force solution finds the earliest and latest dates in
daily_attendance, steps day by day across the calendar, and for each day scans all attendance rows per employee to verify a'Y'record exists. WithDcalendar days in the span,Eemployees, andRrows, that takesO(D * E * R)work — and if two attendance records are years apart,Dis huge even when only a handful of rows exist.The problem becomes much cleaner when we split it into two independent stages:
- Find qualifying dates: Group
'Y'records by date and keep only dates whose present employee count equals the total number of employees. - Find the longest consecutive streak: Sort those qualifying dates and measure the longest run where each date is
1calendar day after the previous one.
- Find qualifying dates: Group
Step 1 in SQL: find dates where every employee was present
A common trap in SQL is checking "every row recorded on this date has
status = 'Y'." That fails whenever an employee has no row at all on that date. Instead, filter tostatus = 'Y'first, group byattendance_date, and verify that the count of distinct present employees matches the full headcount inemployees:-- Keep only dates where every employee in the company has a confirmed 'Y' row SELECT attendance_date FROM daily_attendance WHERE status = 'Y' GROUP BY attendance_date HAVING COUNT(DISTINCT employee_id) = (SELECT COUNT(*) FROM employees)Because
daily_attendance.employee_idreferencesemployeesand(employee_id, attendance_date)is the primary key, the count can reach(SELECT COUNT(*) FROM employees)if and only if every employee has a'Y'row on that date.Step 2 in SQL: group consecutive dates with date minus row number
Once we have the qualifying dates, we need to group adjacent calendar days into unbroken runs — a classic gaps-and-islands problem (grouping consecutive items into "islands" separated by missing-value "gaps").
In SQL, we solve this cleanly using a CTE (Common Table Expression) — a named temporary result defined with
WITH name AS (...)— andROW_NUMBER(), a window function (a function that numbers ordered rows1, 2, 3, ...without collapsing them). Look at what happens when we subtract each row's sequential number (in days) fromattendance_dateacross the March-to-April boundary in Example 1:attendance_date row_num attendance_date - row_num (anchor date) 2025-03-30 1 2025-03-29 \ 2025-03-31 2 2025-03-29 |-- same anchor -> Island A (length 3) 2025-04-01 3 2025-03-29 / [gap on Apr 02] 2025-04-03 4 2025-03-30 \--- new anchor -> Island B (length 1)Inside an unbroken streak, both the calendar date and
row_numadvance by+1per row, so their difference stays frozen at the exact same anchor date! Whenever a calendar gap skips one or more days, the date jumps by more than1whilerow_numstill steps by+1, shifting the anchor to a brand-new date.WITH qualifying AS ( -- Phase 1: Find dates where every employee in employees has status = 'Y' SELECT attendance_date FROM daily_attendance WHERE status = 'Y' GROUP BY attendance_date HAVING COUNT(DISTINCT employee_id) = (SELECT COUNT(*) FROM employees) ), islands AS ( -- Phase 2: Consecutive dates share the same (date - row_number) anchor date. -- Cast ROW_NUMBER() from bigint to INTEGER so PostgreSQL's (date - integer) operator applies. SELECT attendance_date, attendance_date - CAST(ROW_NUMBER() OVER (ORDER BY attendance_date) AS INTEGER) AS island_anchor FROM qualifying ), runs AS ( -- Phase 3: Count how many consecutive days belong to each island SELECT island_anchor, COUNT(*) AS run_length FROM islands GROUP BY island_anchor ) -- COALESCE turns NULL (when zero dates qualify) into 0 SELECT COALESCE(MAX(run_length), 0) AS longest_streak FROM runs;Step 1 in Python: collect and sort qualifying dates
Now let's write the exact same Phase 1 and Phase 2 logic in Python for the automated judge. We convert
employeesinto a setall_employees(a collection of unique items withO(1)membership lookup) and build a dictionarypresent_by_datemapping each date string'YYYY-MM-DD'to the set of employees who hadstatus == 'Y'on that day.Whenever
len(present_ids) == total_employees, every employee was confirmed present, so we parse the string into adatetime.dateobject withdate.fromisoformat(...)and sort all qualifying dates chronologically.from datetime import date, timedelta from typing import Dict, List, Set def qualifying_dates(employees: List[int], daily_attendance: List[List[str]]) -> List[date]: # all_employees: set of distinct employee IDs in the company (e.g. {10, 20, 30}) all_employees: Set[int] = set(employees) total_employees = len(all_employees) if total_employees == 0: return [] # present_by_date: dict mapping 'YYYY-MM-DD' -> set of present employee IDs # e.g. {'2025-03-30': {10, 20, 30}, '2025-04-02': {10, 30}} present_by_date: Dict[str, Set[int]] = {} # Phase 1: Group confirmed 'Y' check-ins by date. Both 'N' rows and missing # rows stay out of the set, so neither counts as confirmed attendance. for employee_id, attendance_date, status in daily_attendance: if status == "Y" and employee_id in all_employees: if attendance_date not in present_by_date: present_by_date[attendance_date] = set() present_by_date[attendance_date].add(employee_id) # Phase 2: Keep only dates where the present headcount matches the full workforce, # convert ISO strings to real calendar dates, and sort chronologically. valid_dates: List[date] = [] for attendance_date, present_ids in present_by_date.items(): if len(present_ids) == total_employees: valid_dates.append(date.fromisoformat(attendance_date)) valid_dates.sort() return valid_datesStep 2 in Python: sweep sorted dates to measure streaks
With
sorted_daysin chronological order, we walk the list once keepingprevious_day,current_streak, andbest_streak:- If
current_day == previous_day + timedelta(days=1), today is immediately after yesterday on the real calendar, socurrent_streak += 1. - Otherwise (either we are at the very first qualifying day, or there was a gap of 2+ days), a brand-new run begins with
current_streak = 1.
Using
timedelta(days=1)ondatetime.dateobjects automatically knows that2025-03-31 + 1 dayis2025-04-01, and that2024-02-28 + 1 dayis2024-02-29in a leap year.from datetime import date, timedelta from typing import List, Optional def longest_streak(employees: List[int], daily_attendance: List[List[str]]) -> int: sorted_days = qualifying_dates(employees, daily_attendance) # Phase 3: Sweep chronologically and extend the streak only when today is # literally yesterday + 1 calendar day (handling month ends and leap years). best_streak = 0 current_streak = 0 previous_day: Optional[date] = None for current_day in sorted_days: if previous_day is not None and current_day == previous_day + timedelta(days=1): current_streak += 1 else: # Either the very first qualifying day or a calendar gap broke the run. current_streak = 1 if current_streak > best_streak: best_streak = current_streak previous_day = current_day return best_streak- If
Trace through Example 1
Let's trace
employees = [10, 20, 30](total_employees = 3) on Example 1:Input rows: '2025-03-30': (10, 'Y'), (20, 'Y'), (30, 'Y') '2025-03-31': (10, 'Y'), (20, 'Y'), (30, 'Y') '2025-04-01': (10, 'Y'), (20, 'Y'), (30, 'Y') '2025-04-02': (10, 'Y'), (20, 'N'), (30, 'Y') '2025-04-03': (10, 'Y'), (20, 'Y'), (30, 'Y') Phase 1 & 2 — present_by_date: '2025-03-30': {10, 20, 30} -> len 3 == 3 -> keep date(2025, 3, 30) '2025-03-31': {10, 20, 30} -> len 3 == 3 -> keep date(2025, 3, 31) '2025-04-01': {10, 20, 30} -> len 3 == 3 -> keep date(2025, 4, 1) '2025-04-02': {10, 30} -> len 2 != 3 -> drop (employee 20 was 'N') '2025-04-03': {10, 20, 30} -> len 3 == 3 -> keep date(2025, 4, 3) sorted_days = [2025-03-30, 2025-03-31, 2025-04-01, 2025-04-03] Phase 3 — streak sweep: day = 2025-03-30: previous_day is None -> current_streak = 1, best_streak = 1 day = 2025-03-31: == 2025-03-30 + 1 day -> current_streak = 2, best_streak = 2 day = 2025-04-01: == 2025-03-31 + 1 day -> current_streak = 3, best_streak = 3 day = 2025-04-03: != 2025-04-01 + 1 day (gap) -> current_streak = 1, best_streak = 3 Return: 3Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from datetime import date, timedelta def qualifying_dates(employees: List[int], daily_attendance: List[List[str]]) -> List[date]: # all_employees: set of distinct employee IDs in the company (e.g. {10, 20, 30}) all_employees: Set[int] = set(employees) total_employees = len(all_employees) if total_employees == 0: return [] # present_by_date: dict mapping 'YYYY-MM-DD' -> set of present employee IDs # e.g. {'2025-03-30': {10, 20, 30}, '2025-04-02': {10, 30}} present_by_date: Dict[str, Set[int]] = {} # Phase 1: Group confirmed 'Y' check-ins by date. Both 'N' rows and missing # rows stay out of the set, so neither counts as confirmed attendance. for employee_id, attendance_date, status in daily_attendance: if status == "Y" and employee_id in all_employees: if attendance_date not in present_by_date: present_by_date[attendance_date] = set() present_by_date[attendance_date].add(employee_id) # Phase 2: Keep only dates where the present headcount matches the full workforce, # convert ISO strings to real calendar dates, and sort chronologically. valid_dates: List[date] = [] for attendance_date, present_ids in present_by_date.items(): if len(present_ids) == total_employees: valid_dates.append(date.fromisoformat(attendance_date)) valid_dates.sort() return valid_dates def longest_streak(employees: List[int], daily_attendance: List[List[str]]) -> int: sorted_days = qualifying_dates(employees, daily_attendance) # Phase 3: Sweep chronologically and extend the streak only when today is # literally yesterday + 1 calendar day (handling month ends and leap years). best_streak = 0 current_streak = 0 previous_day: Optional[date] = None for current_day in sorted_days: if previous_day is not None and current_day == previous_day + timedelta(days=1): current_streak += 1 else: # Either the very first qualifying day or a calendar gap broke the run. current_streak = 1 if current_streak > best_streak: best_streak = current_streak previous_day = current_day return best_streak✅ Submit now — all tests should pass.
Intuition & how it works
Picture a wall calendar in an office where a day earns a gold star only if every single employee on the company roster checks in present ('Y'). Once all the gold stars are placed on the calendar, we simply look for the longest unbroken chain of consecutive gold-star days. That cleanly separates two jobs that would otherwise tangle together: first headcount verification (did all E employees check in 'Y' on this date?), and second gaps-and-islands streak counting (grouping consecutive calendar dates into unbroken runs separated by missing-day gaps).
Why do the obvious shortcuts fail? First, checking whether a date has zero 'N' records (MIN(status) = 'Y') gets fooled whenever an employee has no attendance row at all on that date — a missing row is an unconfirmed absence, so you must count 'Y' check-ins against the full roster in employees. Second, treating adjacent rows in the sorted table as consecutive days fails whenever an entire calendar day has zero rows (for example, Jun 13 followed directly by Jun 15), and doing raw integer math on date strings (20250331 + 1 = 20250332) breaks at every month, year, and leap-year boundary. Using real calendar date arithmetic (previous_day + timedelta(days=1) in Python, or subtracting ROW_NUMBER() — a window function that numbers ordered rows 1, 2, 3, ... — from attendance_date inside a CTE, a named WITH subquery in SQL) handles every boundary automatically.
Here is a trace with employees = [10, 20, 30] across five days spanning a month boundary:
Date 'Y' check-ins Roster = 3? Sorted qualifying dates & streak sweep
2025-03-30 {10, 20, 30} Yes ------> day 1: 2025-03-30 -> streak = 1 (best = 1)
2025-03-31 {10, 20, 30} Yes ------> day 2: 2025-03-31 == prev + 1 day -> streak = 2 (best = 2)
2025-04-01 {10, 20, 30} Yes ------> day 3: 2025-04-01 == prev + 1 day -> streak = 3 (best = 3)
2025-04-02 {10, 30} (20=N) No (skipped — creates a calendar gap)
2025-04-03 {10, 20, 30} Yes ------> day 4: 2025-04-03 != prev + 1 day -> reset streak = 1
Final answer = 3
Complexity
Let E be the number of employees, R be the number of rows in daily_attendance, and Q be the number of qualifying dates (Q <= R / E <= R).
- Time: expected
O(E + R + Q log Q). Buildingall_employeestakesO(E)hash-set insertions; scanning theRattendance rows performsO(1)expected-time dictionary and hash set (a unique-element collection withO(1)average lookup) updates per row; checking set sizes visits at mostRdistinct dates inO(1)time each; sorting theQqualifyingdateobjects takesO(Q log Q)time, followed by a singleO(Q)pass to measure streaks. - Space:
O(E + R).all_employeesstoresEIDs,present_by_datestores at most one(date, employee_id)entry per'Y'row (O(R)), andvalid_datesholdsQ <= Rdate objects.
In PostgreSQL, filtering WHERE status = 'Y' and grouping by attendance_date scans daily_attendance once (O(R) with hash aggregation), sorting the Q qualifying dates for ROW_NUMBER() OVER (ORDER BY attendance_date) takes O(Q log Q), and grouping islands takes O(Q).
Edge cases
- Empty
daily_attendance([]):valid_datesis empty, the streak loop does zero iterations, andlongest_streakreturns0(in SQL,COALESCE(MAX(run_length), 0)turnsNULLinto0). - No qualifying date: Every recorded date has at least one
'N'or missing employee;valid_datesis empty and the function returns0. - Missing employee row on an all-
'Y'date: Ifemployees = [4, 8]and only employee4has a'Y'row on2025-06-11,len(present_ids)is1 != 2, so the date is properly rejected. - Completely unrecorded calendar days: If
2025-06-13and2025-06-15both qualify with zero rows on2025-06-14,2025-06-15 != 2025-06-13 + 1 day, resettingcurrent_streakto1. - Month, year, and leap-year boundaries:
2025-03-31 -> 2025-04-01,2023-12-31 -> 2024-01-01, and2023-02-28 -> 2023-03-01are consecutive, whereas2024-02-28 -> 2024-03-01skips leap day2024-02-29(streak = 1). - Longest streak occurs early, not at the end:
best_streakrecords the maximum beforecurrent_streakever resets to1. - Unsorted input rows: Dictionary grouping does not depend on input order, and
valid_dates.sort()orders dates chronologically before the sweep.
Common mistakes
- Checking only recorded rows (
BOOL_AND(status = 'Y')orMIN(status) = 'Y'): This approves dates where2out of3employees logged'Y'and the third employee has no row at all. Always compare the'Y'count againstlen(all_employees)/(SELECT COUNT(*) FROM employees). - Forgetting
WHERE status = 'Y'beforeCOUNT: Counting all rows per date approves dates where everyone has a row even if one of those rows is'N'. - Assuming adjacent qualifying dates are consecutive days: Two adjacent entries in
valid_dates(orLAG(attendance_date)in SQL) can be weeks apart if intervening days failed or had no records; always check that the date difference is literally1day. - Parsing day-of-month integers instead of real
dateobjects: Checkingint(d2[-2:]) == int(d1[-2:]) + 1fails onMar 31 -> Apr 01(01 != 32). Always usedatetime.date+timedelta(days=1)or SQLDATEarithmetic. - Forgetting
COALESCE(..., 0)in SQL:MAX(run_length)over zero qualifying islands returnsNULLinstead of0. - Subtracting
ROW_NUMBER()directly fromDATEin PostgreSQL:ROW_NUMBER()returnsBIGINT, and PostgreSQL hasdate - integerbut nodate - bigintoperator; castROW_NUMBER()toINTEGER(or multiply byINTERVAL '1 day').
Follow-up questions
- How would you return the start and end dates of the winning streak alongside its length? In Python, track
current_start = current_dayeach timecurrent_streakresets to1, and whenevercurrent_streak > best_streak(or ties under a chosen tie-breaker such as earliest start date), save(best_streak, best_start, current_day). In SQL, computeMIN(attendance_date) AS start_date, MAX(attendance_date) AS end_date, COUNT(*) AS run_lengthperisland_anchor, thenORDER BY run_length DESC, start_date ASC LIMIT 1. - How would your logic change if staff members join and leave over time rather than forming a static roster? Add
hire_dateandtermination_datecolumns toemployees, and define a date's target headcount as the number of employees active on that specific date (hire_date <= d AND (termination_date IS NULL OR termination_date >= d)). Then compare each date's'Y'count among active employees against that date's active headcount, deciding upfront whether dates with0active employees should be excluded. - What if weekends and company holidays should not break a consecutive attendance run? Maintain a
company_calendardimension table where working days are numbered sequentially (workday_seq = 1, 2, 3, ..., skipping weekends and holidays). Join qualifying working dates tocompany_calendarand computeworkday_seq - ROW_NUMBER() OVER (ORDER BY workday_seq)(or checkcurrent_seq == previous_seq + 1in Python), so Friday and Monday have consecutive sequence numbers and form a continuous streak.
Follow-up questions
- How would you return the start and end dates of the winning streak alongside its length?
- How would your logic change if staff members join and leave over time rather than forming a static roster?
- What if weekends and company holidays should not break a consecutive attendance run?
Similar questions
- Top Monthly Customers Under Competition Ranking
- Assign Mapped or Fallback Unique IDs to Employees
- Probability of Two Uniform Arrivals Meeting
- Minimum Triangle Path Sum and Two-Dice Stopping Analysis
- Count Elements With Frequency One
- Locate Two Array Indices With a Target Sum
More Agoda interview questions
- Count Elements With Frequency One Easy
- Top Monthly Customers Under Competition Ranking Easy
- Assign Mapped or Fallback Unique IDs to Employees Easy Pro
- Probability of Two Uniform Arrivals Meeting Medium Pro
- Minimum Triangle Path Sum and Two-Dice Stopping Analysis Medium Pro
- Locate Two Array Indices With a Target Sum Medium Pro