Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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




share|improve this question
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). – dmckee Jan 11 '13 at 15:20
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. – DavidC Jan 11 '13 at 16:32
What should the result of (0,8), (8,16), (16,0) be? – Steven Rumbalski Jan 11 '13 at 16:41
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. – Tim Seguine Feb 24 '14 at 22:20
@TimSeguine thank you for your suggestion, I did not know about this opportunity! – user533039 Feb 25 '14 at 10:27

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
(10, 12), (11, 13), (12, 14)
[(10, 14)]
> python
[(23, 1)]
> python
(0,8), (8,16), (16,0)
[(0, 0)]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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