Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exist, return false.
nums?
nums would range from -10^9 to 10^9, unless mentioned otherwise.nums?
nums can be empty or have up to 10^5 elements.nums?
To solve this problem efficiently, we can maintain two variables:
first: This keeps track of the smallest value encountered so far.second: This keeps track of the smallest value encountered after first.The idea is to:
first when a smaller value is found.second if it is greater than first but less than the current value. When second is updated, it implies we have found the second number in the triplet.first and second, it means we have found our triplet.Here’s the Python function to implement the above logic:
def increasingTriplet(nums):
first = second = float('inf')
for n in nums:
if n <= first:
first = n # smallest value
elif n <= second:
second = n # second smallest value
else:
return True # found a value bigger than both 'first' and 'second'
return False
# Example Test Cases
print(increasingTriplet([1, 2, 3, 4, 5])) # Expected output: True
print(increasingTriplet([5, 4, 3, 2, 1])) # Expected output: False
print(increasingTriplet([2, 1, 5, 0, 4, 6])) # Expected output: True
nums. This is because we are doing a single pass over the array.This efficient solution meets the requirements and constraints of the problem statement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?