KatInterview

Find the First Free Slot After Busy Minutes in Text Schedules

Greedy & IntervalsAuto-graded · 26 test cases
MediumAuto-gradedGreedy & Intervalsintervalsmerge-intervalsstring-parsing

Last updated

Parse text schedule entries into inclusive minute intervals, merge them, and find the earliest k-minute free slot that follows the first busy minute of the day.

Find the First Free Slot After Busy Minutes in Text Schedules

A group of people must all attend a single meeting that lasts k minutes. Their commitments are given as a list of text records. Each record has four fields separated by single spaces: a person's name, an activity, a start time and an end time. For example: "Sam sleep 02:00 10:00".

Return the earliest time the meeting can begin, formatted as "HH:MM", or "-1" if no valid start exists on that day.

Rules

  • The day runs from minute 00:00 to minute 23:59. A record with start a and end b marks every minute from a to b as busy, including both endpoints. For instance, "Lilly exercise 12:00 12:59" blocks exactly 60 minutes.
  • A minute is free if no record covers it. Records may overlap, whether they belong to the same person or to different people. Names and activities have no effect on the result.
  • A meeting starting at minute s uses minutes s through s + k - 1. Every one of those minutes must be free, and the final one must be no later than 23:59.
  • The meeting must start after the first busy minute of the day. Free time before the earliest busy minute is not eligible.
  • Return the earliest valid start as "HH:MM" with a two-digit hour and a two-digit minute, or "-1" if there is none.

Constraints

  • 1 <= len(schedules) <= 10^4
  • Each record has exactly four fields separated by single spaces. The name and the activity are nonempty strings of English letters.
  • Both times are valid zero-padded HH:MM values from 00:00 to 23:59, and the start time is not later than the end time.
  • 1 <= k <= 1440

Examples

Example 1

Input: first_free_slot(['Sam sleep 02:00 10:00', 'Lilly exercise 12:00 12:59'], 90)

Output: '10:01'

Example 2

Input: first_free_slot(['Sam sleep 02:00 10:00', 'Lilly exercise 12:00 12:59'], 180)

Output: '13:00'

Example 3

Input: first_free_slot(['Ann work 08:00 11:00', 'Bo gym 10:30 12:00', 'Cy call 12:30 23:30'], 30)

Output: '-1'

Hints

Hint 1

Convert each HH:MM into a minute number from 0 to 1439. Names and activities can be ignored entirely, so each record becomes one closed interval [a, b].

Hint 2

Because both endpoints are busy, intervals like [600, 700] and [701, 800] leave no free minute between them. Sort and merge whenever the next start is at most the current end plus one.

Hint 3

Since the meeting must come after the first busy minute, the only candidate starts are the minute right after a merged block ends. Check each gap in order, using 1440 as the end for the last block, and stop at the first gap with at least k free minutes.