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?- A. True True True False
- B. False False True False
- C. True False False False
- 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
- Problem: Delete repeated letters so each letter appears once, and among all such results return the lexicographically smallest (a…
- Problem: A game board has scores a[0..n−1]; from cell i you may jump forward 1..k cells. Starting at 0 and ending at n − 1, maximise the…
- Problem: A council of two parties, R and D, votes in rounds in seat order. On their turn a member bans the next opposing member who has…
- Problem: People stand in a line facing right with distinct heights. Person i can see person j > i if everyone strictly between them is…
- Problem: An employee's day is 'tiring' if they worked more than 8 hours. Find the longest run of consecutive days in which tiring days…
- Problem: A sorted list of ticket prices is searched with Python's bisect module. python from bisect import bisectleft, bisectright a =…