The increasing triplet subsequence problem in Python

The increasing triplet subsequence problem involves finding a subsequence in a larger numerical array nums, provided in the function definition. This subsequence should be of length 3, in which the elements should be arranged in ascending order. If this subsequence is found, True should be returned. Otherwise, False is returned. An illustration of this problem is provided below:

Let's look at the array of numbers:

%0 node_1 3 node_2 4 node_3 5 node_1687856452488 4 node_1687856532321 3
Numerical array with triplet ascending subsequence

As denoted by the green elements, a triplet ascending subsequence is present in the array, hence, True will be returned.

Solution

The solution to this problem is provided below:

def increasing_triplet(nums):
least = float('inf')
second = float('inf')
for i in nums:
if i <= least:
least = i
elif i <= second:
second = i
else:
return True
return False
if __name__ == "__main__":
nums = [3, 4, 5, 4, 3]
nums2 = [3, 4, 3, 4, 3]
result = increasing_triplet(nums)
print(result)
result = increasing_triplet(nums2)
print(result)

Code explanation

  • Line 1: We define the increasing_triplet function.

  • Lines 2–3: We declare two variables with infinity as their value, which are used to store the least and the second-least value in the nums array.

  • Line 5: We loop through the nums array.

  • Lines 6–7: We check if the current element is less than the least value encountered so far. If it is, update the value of least.

  • Lines 8–9: We check if the current element exceeds the second-least value encountered. If it isn't, update the value of second.

  • Lines 11–12: If neither of these conditions holds, we have found an increasing triplet and return True. If a triplet wasn't found, we return False.

  • Lines 14–20: This is the code for our main function, which runs the function above.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved