Skip to content
Problem 334 · LeetCode 334(opens in a new tab)

Increasing Triplet Subsequence

MediumArrays

You get a list of whole numbers, nums. Decide whether it holds three numbers that rise strictly from left to right: positions i < j < k with nums[i] < nums[j] < nums[k].

The three numbers do not have to sit next to each other. Return true if such a triple exists and false if it does not.

Example 1

Input:  nums = [6, 2, 9, 1, 4, 7]
Output: true
Why:    1, 4 and 7 rise and appear in that order
2 more examples and the constraints

Example 2

Input:  nums = [9, 7, 7, 4, 2]
Output: false
Why:    the values only fall or stay the same

Example 3

Input:  nums = [5, 5, 8, 8]
Output: false
Why:    5 < 8 is one step up; equal values do not count

Constraints

  • 1 ≤ length of nums ≤ 500,000
  • Every number fits in a 32-bit signed integer
  • Follow-up: O(n) time and O(1) extra space

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every middleO(n²)
  2. Smallest left, largest rightO(n)
  3. Two running minimumsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 500,000 numbersVerdict
Try every middleO(n²)
Mention it, then move on
Smallest left, largest rightO(n)
Passes; costs an extra array
Two running minimumsO(n)
Best; one pass, no extra memory

n = how many numbers are in the list.

Edge cases to test

  • Fewer than three numbers. [3, 8] can never hold a triple: false.
  • Equal values. [5, 5, 8, 8] is false; each step up must be strict.
  • A low number arrives late. [5, 6, 1, 2] is false even though first drops to 1; [2, 5, 1, 6] is true because 6 beats the earlier pair 2 < 5.
  • Extreme values. The largest 32-bit number can be the third number, so start the trackers above it, or use infinity.

Common mistakes

  • Using < instead of ≤ when updating, so repeated values count as rising.
  • Thinking first and second must be the triple itself and resetting second when first drops.
  • Looking only at neighbours; the three numbers can be far apart.

How to talk through it

  1. 1Clarify. Must the rise be strict? Do the positions have to be next to each other? Can the list be shorter than three?
  2. 2Give the slow version. Try every middle and scan both sides; O(n²), too slow for 500,000 numbers.
  3. 3Precompute the sides. Smallest to the left and largest to the right make it O(n) with O(n) memory.
  4. 4Squeeze to two variables. Keep the lowest start and the lowest middle; explain why second stays valid after first drops.
  5. 5Test out loud. Run [5, 5, 5], [5, 6, 1, 2] and [2, 5, 1, 6].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?