Problem · Array

Merge Weekday and Time Intervals

Learn this problem
MediumNextdoor logoNextdoorFULLTIMEPHONE SCREEN

Problem statement

You are given an array of closed time intervals within one Monday-to-Sunday week. Each interval uses the canonical format Day HH:MM -> Day HH:MM, where Day is one of Mon, Tue, Wed, Thu, Fri, Sat, or Sun, and each time uses 24-hour notation.

Merge every pair of intervals that overlaps or shares an endpoint. Return the merged intervals in ascending chronological order, using the same canonical format.

All input intervals are valid, do not wrap past the end of Sunday, and have a start time no later than their end time. Intervals may arrive in any order.

Function

mergeWeeklyIntervals(intervals: String[]) → String[]

Examples

Example 1

intervals = ["Mon 09:00 -> Mon 12:00","Mon 12:00 -> Mon 17:00","Tue 10:00 -> Tue 11:00"]return = ["Mon 09:00 -> Mon 17:00","Tue 10:00 -> Tue 11:00"]

The two Monday intervals share the endpoint Mon 12:00, so they merge. The Tuesday interval remains separate.

Example 2

intervals = ["Wed 10:30 -> Thu 09:00","Tue 18:00 -> Wed 10:30","Fri 08:00 -> Fri 09:00"]return = ["Tue 18:00 -> Thu 09:00","Fri 08:00 -> Fri 09:00"]

After chronological sorting, the first two intervals touch at Wed 10:30 and become one cross-day interval.

Example 3

intervals = ["Sun 23:00 -> Sun 23:59","Mon 00:00 -> Mon 00:30","Mon 00:10 -> Mon 01:00"]return = ["Mon 00:00 -> Mon 01:00","Sun 23:00 -> Sun 23:59"]

The two Monday ranges overlap and merge. The Sunday range is later in the same week and remains separate.

Constraints

  • 1 <= intervals.length <= 100000
  • Every entry has the exact form Day HH:MM -> Day HH:MM.
  • Every time is between 00:00 and 23:59, inclusive.
  • Every interval stays within one Monday-to-Sunday week and has start <= end.
drafts saved locally
public String[] mergeWeeklyIntervals(String[] intervals) {
    // Write your code here.
}
intervals["Mon 09:00 -> Mon 12:00","Mon 12:00 -> Mon 17:00","Tue 10:00 -> Tue 11:00"]
expected["Mon 09:00 -> Mon 17:00", "Tue 10:00 -> Tue 11:00"]
checking account