Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Envelopes [w, h] nest only if both dimensions are strictly smaller. Find the longest nesting chain by sorting and then running LIS on the heights.
Problem: Envelopes [w, h] nest only if both dimensions are strictly smaller. Find the longest nesting chain by sorting and then running LIS on the heights.
from bisect import bisect_left
def dolls(env):
env.sort(key=lambda e: (e[0], -e[1]))
t = []
for _, h in env:
i = bisect_left(t, h)
if i == len(t): t.append(h)
else: t[i] = h
return len(t)
print(dolls([[4,5],[4,6],[6,7],[2,3],[1,1],[6,8],[5,4],[3,2]]))What is printed?- A. 6
- B. 5
- C. 4
- D. 3
Correct answer: C. 4
Sorting widths ascending but heights DESCENDING for equal widths stops two envelopes of the same width ([4,5] and [4,6], or [6,7] and [6,8]) from both entering the strictly increasing run. The best chain has 4 envelopes, e.g. [1,1] → [2,3] → [4,5] → [6,7]; sorting heights ascending would wrongly report 6.
More Coding Interview Problems questions
- Problem: Can the array be split into k subsets with equal sums? (Backtracking over bucket fills.) python def can(a, k): s = sum(a) if s %…
- Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c. python def flips(a, b, c): res = 0 while a or b or…
- Problem: Enumerate all non-empty submasks of a mask with the s = (s − 1) & m trick. python m = 0b101101 s, cnt = m, 0 while s: cnt += 1 s…
- A bitmask DP loops over every mask of n bits and, for each mask, over all of its submasks. What is the total number of (mask, submask)…
- Problem: A dynamic array doubles its capacity when full (starting at capacity 1), copying all elements to the new storage. Count element…
- Problem: A Rabin–Karp search uses a weak hash (the sum of character codes) and verifies every hash hit. Count true matches and spurious…