Increasing Triplet Subsequence

MediumArrays · Greedy🧩 Array ManipulationLeetCode #334 ↗Updated

Problem

Given an integer array nums, decide whether it contains three positions i < j < k whose values are strictly increasing: nums[i] < nums[j] < nums[k]. The three positions do not have to be adjacent. Return true or false.
Inputnums = [2,1,5,0,4,6]Outputtrue (e.g. 1 < 4 < 6)
Inputnums = [5,4,3,2,1]Outputfalse
Inputnums = [1,1,1,2]Outputfalse (equal values don't count)

1 ≤ n ≤ 5·105  ·  -231 ≤ nums[i] ≤ 231-1  ·  Follow-up: O(n) time and O(1) space.

Try it yourself

Java
class Solution {
    public boolean increasingTriplet(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Keep the smallest possible tail of an increasing pair: the smallest value seen (first) and the smallest value that has something smaller before it (second). Any number above second completes a triplet.
PatternArray Manipulation

Instinct "In place", "O(1) extra space" or "one pass" over an array? Think write pointer, reversal, prefix/suffix passes or using indices as storage.

Memory hack Read fast, write slow, reverse to rotate, and let the index be the hash.

Open the Array Manipulation guide →

Approaches

Brute ForceCheck Every Triple

Time O(n3)Space O(1)

Three nested loops pick i < j < k and test the strict ordering. Skipping the inner loops when nums[j] ≤ nums[i] helps a little but the worst case is still cubic.

Java
public boolean increasingTriplet(int[] nums) {
    int n = nums.length;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (nums[j] <= nums[i]) continue;
            for (int k = j + 1; k < n; k++) {
                if (nums[k] > nums[j]) return true;
            }
        }
    }
    return false;
}

Correct and tiny, but hopeless at n = 5·105.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every TripleO(n3)O(1)
BetterPrefix Minimum + Suffix MaximumO(n)O(n)
OptimalGreedy — Two Smallest TailsO(n)O(1)
Common pitfalls
  • Using < instead of <= — equal values sneak in as an “increasing” step.
  • Thinking first, second must be the actual triplet — after an update, first may sit after second.
  • Looking only at adjacent elements — the triplet is a subsequence, not a subarray.
Interview tips
  • Explain why the stale first is fine: second alone certifies a smaller earlier value.
  • Present the prefix-min/suffix-max version first; it makes the “middle element” view concrete.
  • Mention the generalisation: this is LIS with patience sorting, stopped at length 3.
Pattern
Greedy smallest tails → detect an increasing subsequence of fixed length k in O(n·k) time and O(k) space.
My notes saved in this browser