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?
  1. A. 6
  2. B. 5
  3. C. 4
  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

Exams that ask this topic