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 public boolean increasingTriplet(int[] nums) {
3 int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
4 for (int num : 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}
This Java solution follows the same logic as the C solution. It uses enhanced for loop for iteration and checks if the current number is part of a valid increasing triplet by comparing it with first
and second
.
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.