Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Does a price series contain a '132' pattern – indices i < j < k with a[i] < a[k] < a[j]? Scan from the right with a decreasing stack, remembering the largest value popped (the best candidate for a[k]).

Problem: Does a price series contain a '132' pattern – indices i < j < k with a[i] < a[k] < a[j]? Scan from the right with a decreasing stack, remembering the largest value popped (the best candidate for a[k]).
def has_132(a):
    st, third = [], float("-inf")
    for x in reversed(a):
        if x < third: return True
        while st and st[-1] < x:
            third = st.pop()
        st.append(x)
    return False
print(has_132([4, 6, 2, 5, 1]), has_132([1, 2, 3, 4]), has_132([3, 5, 0, 3, 4]), has_132([5, 4, 3, 6]))
What is printed?
  1. A. True True True False
  2. B. False False True False
  3. C. True False False False
  4. D. True False True False

Correct answer: D. True False True False

Going right-to-left, when x pops smaller values, the popped value is a valid 'a[k]' with x as the larger 'a[j]' to its left; 'third' keeps the largest such a[k]. Any later (further left) value below third completes the pattern. [4, 6, 2, 5, 1]: 4 < 5 < 6 → True. [3, 5, 0, 3, 4]: 3 < 4 < 5 → True. Strictly increasing or [5, 4, 3, 6] has none. O(n) versus O(n³) brute force or O(n²) with prefix minima.

More Coding Interview Problems questions

Exams that ask this topic