Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Detect a 132 pattern (i < j < k with a[i] < a[k] < a[j]) in O(n) by scanning from the right with a stack.

Problem: Detect a 132 pattern (i < j < k with a[i] < a[k] < a[j]) in O(n) by scanning from the right with a stack.
def has132(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(has132([3, 5, 0, 3, 4]), has132([1, 2, 3, 4]), has132([6, 12, 3, 4, 6, 11, 20]))
What is printed?
  1. A. True False False
  2. B. False False True
  3. C. True False True
  4. D. True True True

Correct answer: C. True False True

'third' is the best candidate for a[k]: the largest value popped by a bigger a[j] to its left. [3, 5, 0, 3, 4]: 3 < 4 < 5 (indices 0, 1, 4) → True. A sorted array has none. In the third, 6 < 11 < 12 with 12 appearing before 11 → True.

More Coding Interview Problems questions

Exams that ask this topic