InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Greedy

Increasing Triplet Subsequence

medium Original ↗ 00:00

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]True1 < 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 follow-up “can you do it in O(n) time and O(1) space?” rule out the cubic and quadratic solutions.

Think about it first

Hint 1 A triplet needs a small value, a middle value larger than some earlier value, and any later value larger than that middle. 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, a triplet exists.
Hint 3 Lower first and second whenever you can. first may later point to an element positioned after the one that set second, which looks out of order. But once second was set, a smaller value did precede it, so any value greater than second still proves a triplet.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug