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.
1public class Solution {
2 public bool IncreasingTriplet(int[] nums) {
3 int first = int.MaxValue, second = int.MaxValue;
4 foreach (int num in nums) {
5 if (num <= first) {
6 first = num;
7 } else if (num <= second) {
8 second = num;
9 } else {
10 return true;
11 }
12 }
13 return false;
14 }
15}
Similar to other languages, the C# solution iteratively adjusts first
and second
while checking for the existence of an increasing triplet.
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.