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.
1var increasingTriplet = function(nums) {
2 let first = Number.MAX_SAFE_INTEGER, second = Number.MAX_SAFE_INTEGER;
3 for (let num of nums) {
4 if (num <= first) {
5 first = num;
6 } else if (num <= second) {
7 second = num;
8 } else {
9 return true;
10 }
11 }
12 return false;
13};
This JavaScript solution adopts similar logic, where first
and second
are updated and checked for formation 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.
1#include <stdbool.h>
2
This solution creates two arrays, leftMin
and rightMax
, to store the minimum values to the left and maximum values to the right of each element. It then checks for a valid increasing triplet by ensuring there's a middle element greater than the minimum from the left and less than the maximum from the right.