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:
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 = ielif i <= second:second = ielse:return Truereturn Falseif __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_tripletfunction.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
numsarray.Line 5: We loop through the
numsarray.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 returnFalse.Lines 14–20: This is the code for our
mainfunction, which runs the function above.
Free Resources