InterviewPrepKit

Home / Coding / Greedy

Increasing Triplet Subsequence

medium Original β†—
Solving tips
  • Track two running minima: first = smallest seen, second = smallest value that has something smaller before it; any element beating second proves a triplet.
  • Use <= (not <) in the comparisons so duplicate values don't spuriously advance to second.
  • Don't be spooked when first ends up positioned after the element that set second β€” the proof relies only on the history at assignment time, so no false positives occur.
  • Aim for O(n) time and O(1) space; this generalizes to the patience-sorting O(n log n) longest-increasing-subsequence idea.

Problem

Given an integer array nums, decide whether there exist three indices i < j < k such that nums[i] < nums[j] < nums[k]. Return True if such an increasing triplet (not necessarily contiguous) exists, False otherwise.

You only need to report existence β€” you do not have to return the indices.

Examples

  • nums = [1,2,3,4,5] β†’ True β€” 1 < 2 < 3 (many triplets work).
  • nums = [5,4,3,2,1] β†’ False β€” strictly decreasing, so no increasing triple exists.
  • nums = [2,1,5,0,4,6] β†’ True β€” the triplet 1 < 4 < 6 (indices 1, 4, 5) increases.

Constraints

  • 1 <= len(nums) <= 5 * 10^5
  • -2^31 <= nums[i] <= 2^31 - 1

The half-million bound and the β€œcan you do it in O(n) time and O(1) space?” follow-up steer you away from the cubic and quadratic solutions.

Think about it first

Hint 1 A triplet needs a "small," a "medium bigger than the small seen earlier," and any "large bigger than that medium." What two running values would you track as you scan left to right?
Hint 2 Keep first = smallest value seen so far, and second = smallest value that has some smaller value before it. If any later number exceeds second, you are done.
Hint 3 Greedily lower first and second whenever you can. It looks suspicious that first might later refer to an element positioned after second β€” but convince yourself that once second was set, a valid first genuinely existed before it, so seeing any value greater than second proves a triplet.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.