LearnFrenzy
Sign in Take a free test

Python Coding Interview Questions · Find the Bug · Question 10

Bug: intervals merged without sorting Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

[[8, 10], [1, 3], [2, 6]] should merge to [[1, 6], [8, 10]], but the program prints [[8, 10]]. Which statement correctly identifies the bug?

main.py
def merge(intervals):
    merged = []
    for start, end in intervals:
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged

print(merge([[8, 10], [1, 3], [2, 6]]))
  • A max() should be min()
  • B The algorithm assumes intervals are sorted by start; sort them first with sorted(intervals) Correct
  • C <= should be <
  • D merged must be a tuple
Correct Answer: Option B

Unsorted, [1, 3] and [2, 6] look like they overlap [8, 10] because their starts are smaller than 10, so they are swallowed. Only after sorting by start is it enough to compare each interval with the last merged one.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links