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?- A. 6
- B. 5
- C. 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
- Problem: Paint a row of houses with 3 colours so that neighbours differ; costs[i] = cost of each colour for house i. Minimise the total…
- Problem: Split an integer n ≥ 2 into at least two positive parts to maximise the product of the parts. python def intbreak(n): dp = [0, 1]…
- Problem: A cable of length n is cut into pieces; prices[k − 1] is the price of a piece of length k. Maximise revenue (unbounded knapsack)…
- Problem: Count subsets of distinct-position items whose values sum exactly to the target (0/1 counting knapsack with a 1-D array iterated…
- Problem: Compare the longest common SUBSTRING (contiguous) with the longest common SUBSEQUENCE of two log fragments. python def lcsub(a…
- Problem: Find the length of the shortest string that contains both a and b as subsequences: |a| + |b| − LCS(a, b). python def lcs(a, b)…