Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Does an array contain indices i < j < k with a[i] < a[j] < a[k]? An O(n), O(1) greedy keeps the smallest 'first' and the smallest 'second' seen so far.
Problem: Does an array contain indices i < j < k with a[i] < a[j] < a[k]? An O(n), O(1) greedy keeps the smallest 'first' and the smallest 'second' seen so far.
def inc_triplet(a):
first = second = float("inf")
for x in a:
if x <= first: first = x
elif x <= second: second = x
else: return True
return False
print(inc_triplet([6, 2, 7, 1, 8]), inc_triplet([5, 4, 3, 2]), inc_triplet([2, 5, 1, 3]), inc_triplet([4, 6, 1, 7]))What is printed?- A. True False False False
- B. True False False True
- C. False False False True
- D. True False True True
Correct answer: B. True False False True
second always means 'some value before it was smaller'. In [4, 6, 1, 7], first becomes 1 after second = 6 was set, but second = 6 still certifies the pair (4, 6), so 7 > 6 returns True – the trap is thinking first must precede second. [2, 5, 1, 3] ends with first = 1, second = 3 and no larger value → False. [6, 2, 7, 1, 8]: 2 < 7 < 8 → True.
More Coding Interview Problems questions
- Problem: Can a hand of cards be split into groups of exactly w consecutive values? Greedily start groups at the smallest remaining card…
- Problem: Swap at most two digits of a number once to obtain the maximum value. Record the last position of each digit and, scanning left…
- Problem: Flower i blooms on day bloom[i]. A bouquet needs k ADJACENT bloomed flowers, each flower used once. Find the minimum day by which…
- Problem: A number is 'magical' if it is divisible by a or b. Find the n-th magical number by binary search with inclusion–exclusion…
- Problem: Find the maximum difference between successive values in the SORTED order of an array, in linear time, using buckets (pigeonhole…
- Problem: Camera clips (start, end) cover parts of an event lasting T = 10 minutes; clips may be trimmed. Find the minimum number of clips…