You have an array of working time period pairs (from, till) received from user input and written according 24-hour clock format convention. You have to merge these periods if the intersect each other.

For example, if you have (10, 12), (11, 13), (12, 14) you should merge them into (10,14). Also (23, 0) and (0, 1) should be merged into (23, 1).


@dmckee Let assume that the set of pairs like (10:00, 12:00) is the valid input.

@dude We don't consider Sundays and holidays so all merges should be performed for the common twenty-four hours range.

@steven-rumbalski The result of (0,8), (8,16), (16,0) may be any (x,x) pair, for example, (00:00,00:00).

Example 1





Example 2




  • 3
    \$\begingroup\$ Is (10,12) a valid input, or should it be (10:00, 12:00) or something similar? Likewise, what is the correct format for the output? Also each challenge should specify what the metric is (i.e. we don't only do [code-golf] or even default to it). \$\endgroup\$ Jan 11, 2013 at 15:20
  • 1
    \$\begingroup\$ Because one work shift can spill over from one day into the next [as (23,0)+(0,1) =(23,1) appears to show], shouldn't we be keeping track of the days in the workweek also? If Sunday is not a work day, it would seem that (23,1), starting Sunday Evening and going to 1 am Monday, would not count. However, from Monday to Tuesday, it would be counted. \$\endgroup\$
    – DavidC
    Jan 11, 2013 at 16:32
  • 3
    \$\begingroup\$ What should the result of (0,8), (8,16), (16,0) be? \$\endgroup\$ Jan 11, 2013 at 16:41
  • 1
    \$\begingroup\$ In the future, maybe post your spec to the sandbox on meta first to get feedback before you post. This could have been a great question with a little more work. \$\endgroup\$ Feb 24, 2014 at 22:20
  • \$\begingroup\$ @TimSeguine thank you for your suggestion, I did not know about this opportunity! \$\endgroup\$
    – user533039
    Feb 25, 2014 at 10:27

1 Answer 1


Python (198 chars)

l=r+sorted(a<b and (a,b)or p((0,b))or(a,24)for a,b in input())
for c,d in l[1:]:
 if c>b:p((a,b));a,b=c,d
 elif b<d:b=d
if b>23:b=a and r.pop(0)[1]
print r


> python merge.py
(10, 12), (11, 13), (12, 14)
[(10, 14)]
> python merge.py
[(23, 1)]
> python merge.py
(0,8), (8,16), (16,0)
[(0, 0)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.