Table of Contents
Increasing Triplet Subsequence
Problem Statement
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
.
Example 1
Input: nums = [1,2,3,4,5] Output: true Explanation: Any triplet where i < j < k is valid.
Example 2
Input: nums = [5,4,3,2,1] Output: false Explanation: No triplet exists.
Example 3
Input: nums = [2,1,5,0,4,6] Output: true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
Constraints
1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
Follow up
Could you implement a solution that runs in O(n)
time complexity and O(1)
space complexity?
Golang Solution Increasing Triplet Subsequence
func increasingTriplet(nums []int) bool {
n := len(nums)
if (n < 3) || (n > (5 * 10 * 10 * 10 * 10 * 10)) {
return false
}
first := math.MaxInt64
second := math.MaxInt64
for i := 0; i < n; i++ {
if nums[i] <= first {
first = nums[i]
} else if nums[i] <= second {
second = nums[i]
} else {
return true
}
}
return false
}
Explanation
first
stores the smallest value seen so far.second
stores the second smallest value.- As we traverse the array, we update
first
andsecond
if possible. If we find any number greater than both, it confirms the existence of an increasing triplet subsequence.
Time Complexity
- O(n) since we are iterating through the array once.
Space Complexity
- O(1) since we only use a few variables to track the smallest values.
This approach is optimal and works efficiently for large input arrays.
If you’d like to see another solution, like dynamic programming or a different approach, let me know!
Visit https: https://codeandalgo.com for more such contents
Leave a Reply