Sponsored
Sponsored
This approach leverages two variables to track the smallest and the second smallest elements found so far in the array. As you traverse through the array, you update these two variables. If you find an element greater than the second smallest, then a triplet exists, and you return true
.
Time Complexity: O(n), where n is the length of the input list, as we only traverse the list once.
Space Complexity: O(1), since we are using only a constant amount of extra space.
1class Solution:
2 def increasingTriplet(self, nums: List[int]) -> bool:
3 first, second = float('inf'), float('inf')
4 for num in nums:
5 if num <= first:
6 first = num
7 elif num <= second:
8 second = num
9 else:
10 return True
11 return False
The Python solution uses simple comparison logic to update first
and second
. Upon finding a number larger than both, it returns True
.
This approach uses an auxiliary array to keep track of the minimum elements on the left and the maximum elements on the right for each position in the array. The main idea is to check if there's any element that can serve as the middle element between some smaller and a larger element.
Time Complexity: O(n), due to traversals of size n.
Space Complexity: O(n), since it uses extra space for two arrays.
1class Solution:
2 def
In this Python solution, leftMin
and rightMax
arrays help identify a valid triplet condition for each middle element.