DEV Community

Arjun Rajkumar
Arjun Rajkumar

Posted on • Edited on

Write better code: Day 6 - Merge Meetings times

Recent posts:


--

Day 6: Question 1

Write a method merge_ranges() that takes an array of multiple meeting time ranges and returns an array of condensed ranges.

For example, given:
[[0, 1], [3, 5], [4, 8], [10, 12], [9, 10]]
Output -> [[0, 1], [3, 8], [9, 12]]

Enter fullscreen mode Exit fullscreen mode

Do not assume the meetings are in order. The meeting times are coming from multiple teams.

Write a solution that's efficient even when we can't put a nice upper bound on the numbers representing our time ranges. Here we've simplified our times down to the number of 30-minute slots past 9:00 am. But we want the method to work even for very large numbers, like Unix timestamps. In any case, the spirit of the challenge is to merge meetings where start_time and end_time don't have an upper bound.

-

If you want to follow along, feel free to post your answers in the comment.

My answers are in the comments.
This problem is from InterviewCake.

Top comments (1)

Collapse
 
arjunrajkumar profile image
Arjun Rajkumar • Edited

Inputs - [[0, 1], [3, 5], [4, 8], [10, 12], [9, 10]]
Output - [[0, 1], [3, 8], [9, 12]]

Logic.

  • Sort the meeting times in ascending order.
  • Then compare the starting time with the previous ending meeting time.
  • If it greater, new meeting time. If lesser, check to see which is max.
  • Using sort and going the meetings once so its O[nlogn]
  • Space is O[n]
def meeting_times(meetings)
  meetings = meetings.sort
  answer = [meetings[0]]

  meetings[1..-1].each do |starting_time, ending_time|
    previous_starting_time, previous_ending_time = answer[-1]

    if starting_time > previous_ending_time
      answer << [starting_time, ending_time]
    else
      answer[-1] = [previous_starting_time, [ending_time, previous_ending_time].max]
    end
  end

  answer
end

Nice Ruby hack: If you have an array e.g.
players = ["pele", "jordan", "sachin"]

Then you can assign each of these to 3 different variables with this one line:
football, basketball, cricket = players

so you get 3 variables:
football = pele
basketball = jordan
cricket = sachin

Easier than doing players[0], players[1] and so on..