LeetCode: Increasing Triplet Subsequence
Find if there exists an increasing triplet subsequence in an array.
See original problem on leetcode.com
Difficulty: Medium
Solution
The constraints state that the maximum value is 2^31 - 1. This is used as the initial values for first and second.
Loop through each val in nums.
- If
valis equal tofirstorsecond, do nothing. - If
valis less thanfirst, updatefirstto beval. - If
valis less thansecond, updatesecondto beval. This means thatsecondis guaranteed to be strictly greater thanfirst. - Otherwise, return
True. This guarantees thatvalis greater than bothfirstandsecond.
Runtime
11 ms | Beats 96.51%
class Solution: def increasingTriplet(self, nums: List[int]) -> bool: first = 2 ** 31 - 1 second = 2 ** 31 - 1
for val in nums: if val == first or val == second: pass elif val < first: first = val elif val < second: second = val else: return True
return False