Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval.
Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval.
def intersect(A, B):
i = j = 0; out = []
while i < len(A) and j < len(B):
lo = max(A[i][0], B[j][0]); hi = min(A[i][1], B[j][1])
if lo <= hi:
out.append((lo, hi))
if A[i][1] < B[j][1]: i += 1
else: j += 1
return out
print(intersect([(1, 4), (6, 9), (12, 15)], [(3, 7), (9, 13)]))What is printed?- A. [(3, 7), (9, 13)]
- B. [(1, 7), (6, 13), (12, 15)]
- C. [(3, 4), (6, 7), (9, 9), (12, 13)]
- D. [(3, 4), (6, 7), (12, 13)]
Correct answer: C. [(3, 4), (6, 7), (9, 9), (12, 13)]
The overlap of two intervals is [max of starts, min of ends] when non-empty; then advance whichever interval ends first, since it cannot meet anything later. Closed intervals that only touch still intersect: (6, 9) and (9, 13) share the single point (9, 9). Dropping it (lo < hi) gives the second option. O(|A| + |B|).
More Coding Interview Problems questions
- Problem: A sensor array is 'steady' between positions i < j if a[j] − a[i] = j − i. Count steady pairs in O(n) by grouping a[i] − i…
- Problem: Four price lists A, B, C, D (each of length n ≤ 500). Count index tuples (i, j, k, l) with A[i] + B[j] + C[k] + D[l] = 0 by…
- Problem: A hiking trail is a list of heights. Find the length of the longest 'ridge' – a contiguous stretch that strictly rises and then…
- Problem: Return the sum of min(sub) over all contiguous subarrays using a monotonic stack. Ties must be broken so every subarray's minimum…
- Problem: Pick two NON-overlapping windows of fixed lengths L and M (either order) to maximise the total of their elements. Prefix sums…
- Problem: Remove the SHORTEST contiguous block (not the whole array) so that the remaining sum is divisible by p; return −1 if impossible…