Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Pairs (a, b) with a < b can be chained when the next pair's a is strictly greater than the previous b. Find the longest chain (pairs may be reordered).

Problem: Pairs (a, b) with a < b can be chained when the next pair's a is strictly greater than the previous b. Find the longest chain (pairs may be reordered).
def chain(pairs):
    cur, cnt = float("-inf"), 0
    for a, b in sorted(pairs, key=lambda p: p[1]):
        if a > cur: cnt += 1; cur = b
    return cnt
print(chain([(5, 9), (1, 3), (2, 4), (4, 6), (7, 8), (10, 12)]))
What is printed?
  1. A. 6
  2. B. 5
  3. C. 4
  4. D. 3

Correct answer: C. 4

This is interval scheduling: sort by end and greedily take each pair that starts after the last chosen end. (1, 3), (4, 6), (7, 8), (10, 12) → 4; (2, 4) and (5, 9) overlap chosen pairs. Sorting by start instead can pick a long early pair and lose. O(n log n), versus O(n²) for the LIS-style DP.

More Coding Interview Problems questions

Exams that ask this topic