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?
  1. A. True False False False
  2. B. True False False True
  3. C. False False False True
  4. 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

Exams that ask this topic