cswork / libraryOpen practice workspace

Coding questions · Agoda

Find the Longest Calendar-Day Streak with All Employees Present

Identify dates when every employee is present and compute the longest consecutive streak, treating missing attendance as a gap.

Find the longest run of consecutive calendar days on which every employee was present.

Input Tables

employees(employee_id INTEGER PRIMARY KEY) contains at least one employee.

daily_attendance(employee_id INTEGER, attendance_date DATE, status TEXT) has a primary key on (employee_id, attendance_date). All fields are non-null, employee identifiers reference employees, and status is either Y for present or N for absent.

Output Contract

Write one read-only PostgreSQL query returning exactly one row with one integer column, longest_streak.

A date qualifies only when every employee in employees has a Y record for that date. A missing record counts as not confirmed present, so that date does not qualify. Return the length of the longest consecutive-date run of qualifying dates, or 0 if none qualify.

Example

There are two employees. Both have Y records on January 1 and January 2. On January 3 one employee has N. Both have Y on January 4.

Expected result:

longest_streak
2

Constraints and Clarifications

  • The employee population is the fixed set in employees throughout this exercise.
  • Consecutive means consecutive calendar dates, including weekends and month boundaries.
  • A date with no attendance records is a gap, even if the nearest recorded dates each qualify.
  • The attendance table may be empty, in which case return 0.
  • Do not infer that all employees attended merely because all records present for a date are Y; some employees may be missing.

Hint: Establish qualifying dates before finding a streak

First compare each day's confirmed attendance with the full employee population. Then measure adjacency between the resulting calendar dates.

Longest Streak of Full-Attendance Days

Table employees

columntypeconstraints
employee_idINTEGERPRIMARY KEY

Sample data:

employee_id
101
102
103

Table daily_attendance

columntypeconstraints
employee_idINTEGERNOT NULL
attendance_dateDATENOT NULL
statusTEXTNOT NULL

Sample data:

attendance_dateemployee_idstatus
2024-01-27101Y
2024-01-27102Y
2024-01-27103Y
2024-01-28101Y
2024-01-28102Y
2024-01-28103Y
2024-01-29101Y
2024-01-29102Y
2024-01-29103N
2024-01-30101Y
2024-01-30102Y
2024-01-30103Y
2024-01-31101Y
2024-01-31102Y
2024-01-31103Y
2024-02-01101Y
2024-02-01102Y
2024-02-01103Y
2024-02-02101Y
2024-02-02102Y
2024-02-03101Y
2024-02-03102Y
2024-02-03103Y
2024-02-04101Y
2024-02-04102Y
2024-02-04103Y
2024-02-06101Y
2024-02-06102Y
2024-02-06103Y
2024-02-07101Y
2024-02-07102Y
2024-02-07103Y

Expected output

longest_streak
3

Hints

  1. Establish qualifying dates before finding a streak: first compare each day's confirmed attendance with the full employee population.
  2. Then measure adjacency between the resulting calendar dates.