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?- A. True False False
- B. False False True
- C. True False True
- 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
- Problem: A single-threaded CPU log has entries 'id:start:t' and 'id:end:t' (an end at t covers time unit t). Functions can call each…
- Problem: Evaluate an expression with +, −, , / (integer division truncating toward zero) and no parentheses, using a stack. python def…
- Problem: Find every start index in s of a substring that is a concatenation of all the given words (each exactly once, any order; all…
- Problem: Find the shortest contiguous substring of S that contains T as a SUBSEQUENCE (leftmost on ties). Scan forward to complete T, then…
- Problem: Find the longest substring that occurs at least twice (occurrences may overlap): binary search on the length with a set of…
- Problem: Count how many words are subsequences of s, by bucketing words by the next character they are waiting for. python from…