Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.
Explanation: Any triplet where i < j < k is valid.
Explanation: No triplet exists.
Explanation: One of the valid triplet is index (3, 4, 5), because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?
The simplest approach to find an increasing triplet subsequence is to use three nested loops to check all possible triplets in the array.
This is a naive solution but helps to understand the underlying concept.
The goal is to find three increasing numbers a, b, c such that a < b < c. We can achieve this in linear time with two variables:
As we scan through the array, the goal is to gradually refine these candidates. If at any point we encounter a number greater than both first and second, it becomes our third, and the triplet exists.
The key idea is that we’re not trying to find the actual triplet, we’re trying to prove that one exists.
The algorithm maintains the strongest possible candidates for forming an increasing triplet:
first as small as possible. A smaller first increases our chances of finding a valid second and third.first, we look for the smallest number greater than first. This ensures the widest possible margin for finding a future third.first and second, we are guaranteed to have: first < second < num (this num is our c).The moment this happens, we can immediately return true.