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:
  • employees lists the distinct integer IDs of every staff member on the roster.
  • daily_attendance is a list of [employee_id, attendance_date, status] rows, where employee_id is an integer from employees, attendance_date is an ISO calendar string 'YYYY-MM-DD', and status is '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 employees has a row with status = '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 (+1 day), continuing seamlessly across weekends, month-ends, year-ends, and leap days.
  • Return 0 when daily_attendance is 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

  • employees contains at least 1 unique integer ID and stays fixed across all dates.
  • daily_attendance may contain 0 or more rows in arbitrary order, with at most one row per (employee_id, attendance_date).
  • Every attendance_date is a valid 'YYYY-MM-DD' Gregorian calendar date, and every status is 'Y' or 'N'.
  • Do not assume full attendance on a date just because zero 'N' records appear on that date; every member of employees must have an explicit 'Y' record.

Step-by-step walkthrough

  1. 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 return 0.

    In the SQL schema we have employees(employee_id) and daily_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, where attendance_date is an ISO date string ('YYYY-MM-DD', such as '2025-06-11') and status is '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 = 1
    

    Weekends, 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.

  2. 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. With D calendar days in the span, E employees, and R rows, that takes O(D * E * R) work — and if two attendance records are years apart, D is huge even when only a handful of rows exist.

    The problem becomes much cleaner when we split it into two independent stages:

    1. Find qualifying dates: Group 'Y' records by date and keep only dates whose present employee count equals the total number of employees.
    2. Find the longest consecutive streak: Sort those qualifying dates and measure the longest run where each date is 1 calendar day after the previous one.
  3. 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 to status = 'Y' first, group by attendance_date, and verify that the count of distinct present employees matches the full headcount in employees:

    -- 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_id references employees and (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.

  4. 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 (...) — and ROW_NUMBER(), a window function (a function that numbers ordered rows 1, 2, 3, ... without collapsing them). Look at what happens when we subtract each row's sequential number (in days) from attendance_date across 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_num advance by +1 per 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 than 1 while row_num still 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;
    
  5. 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 employees into a set all_employees (a collection of unique items with O(1) membership lookup) and build a dictionary present_by_date mapping each date string 'YYYY-MM-DD' to the set of employees who had status == 'Y' on that day.

    Whenever len(present_ids) == total_employees, every employee was confirmed present, so we parse the string into a datetime.date object with date.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_dates
    
  6. Step 2 in Python: sweep sorted dates to measure streaks

    With sorted_days in chronological order, we walk the list once keeping previous_day, current_streak, and best_streak:

    • If current_day == previous_day + timedelta(days=1), today is immediately after yesterday on the real calendar, so current_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) on datetime.date objects automatically knows that 2025-03-31 + 1 day is 2025-04-01, and that 2024-02-28 + 1 day is 2024-02-29 in 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
    
  7. 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: 3
    
  8. Complete 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). Building all_employees takes O(E) hash-set insertions; scanning the R attendance rows performs O(1) expected-time dictionary and hash set (a unique-element collection with O(1) average lookup) updates per row; checking set sizes visits at most R distinct dates in O(1) time each; sorting the Q qualifying date objects takes O(Q log Q) time, followed by a single O(Q) pass to measure streaks.
  • Space: O(E + R). all_employees stores E IDs, present_by_date stores at most one (date, employee_id) entry per 'Y' row (O(R)), and valid_dates holds Q <= R date 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_dates is empty, the streak loop does zero iterations, and longest_streak returns 0 (in SQL, COALESCE(MAX(run_length), 0) turns NULL into 0).
  • No qualifying date: Every recorded date has at least one 'N' or missing employee; valid_dates is empty and the function returns 0.
  • Missing employee row on an all-'Y' date: If employees = [4, 8] and only employee 4 has a 'Y' row on 2025-06-11, len(present_ids) is 1 != 2, so the date is properly rejected.
  • Completely unrecorded calendar days: If 2025-06-13 and 2025-06-15 both qualify with zero rows on 2025-06-14, 2025-06-15 != 2025-06-13 + 1 day, resetting current_streak to 1.
  • Month, year, and leap-year boundaries: 2025-03-31 -> 2025-04-01, 2023-12-31 -> 2024-01-01, and 2023-02-28 -> 2023-03-01 are consecutive, whereas 2024-02-28 -> 2024-03-01 skips leap day 2024-02-29 (streak = 1).
  • Longest streak occurs early, not at the end: best_streak records the maximum before current_streak ever resets to 1.
  • 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') or MIN(status) = 'Y'): This approves dates where 2 out of 3 employees logged 'Y' and the third employee has no row at all. Always compare the 'Y' count against len(all_employees) / (SELECT COUNT(*) FROM employees).
  • Forgetting WHERE status = 'Y' before COUNT: 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 (or LAG(attendance_date) in SQL) can be weeks apart if intervening days failed or had no records; always check that the date difference is literally 1 day.
  • Parsing day-of-month integers instead of real date objects: Checking int(d2[-2:]) == int(d1[-2:]) + 1 fails on Mar 31 -> Apr 01 (01 != 32). Always use datetime.date + timedelta(days=1) or SQL DATE arithmetic.
  • Forgetting COALESCE(..., 0) in SQL: MAX(run_length) over zero qualifying islands returns NULL instead of 0.
  • Subtracting ROW_NUMBER() directly from DATE in PostgreSQL: ROW_NUMBER() returns BIGINT, and PostgreSQL has date - integer but no date - bigint operator; cast ROW_NUMBER() to INTEGER (or multiply by INTERVAL '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_day each time current_streak resets to 1, and whenever current_streak > best_streak (or ties under a chosen tie-breaker such as earliest start date), save (best_streak, best_start, current_day). In SQL, compute MIN(attendance_date) AS start_date, MAX(attendance_date) AS end_date, COUNT(*) AS run_length per island_anchor, then ORDER 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_date and termination_date columns to employees, 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 with 0 active employees should be excluded.
  • What if weekends and company holidays should not break a consecutive attendance run? Maintain a company_calendar dimension table where working days are numbered sequentially (workday_seq = 1, 2, 3, ..., skipping weekends and holidays). Join qualifying working dates to company_calendar and compute workday_seq - ROW_NUMBER() OVER (ORDER BY workday_seq) (or check current_seq == previous_seq + 1 in Python), so Friday and Monday have consecutive sequence numbers and form a continuous streak.

Follow-up questions

Similar questions

More Agoda interview questions

All 7 Agoda questions →