Skip to content

Commit e69822c

Browse files
committed
Increasing triplet subsequence in O(n) time and O(1) space
1 parent 540224a commit e69822c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

increasing_triplet_subsequence.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
2+
#
3+
# Formally the function should:
4+
#
5+
# Return true if there exists i, j, k
6+
# such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
7+
"""
8+
>>> increasing_triplet([1, 2, 3, 4, 5])
9+
True
10+
>>> increasing_triplet([5, 4, 3, 2, 1])
11+
False
12+
>>> increasing_triplet([5, 4, 3])
13+
False
14+
>>> increasing_triplet([1, 2, 3])
15+
True
16+
>>> increasing_triplet([3, 2, 4, 1, 5])
17+
True
18+
>>> increasing_triplet([])
19+
False
20+
>>> increasing_triplet([1, 1, 1])
21+
False
22+
>>> increasing_triplet([5, 1, 5, 5, 2, 5, 4])
23+
True
24+
25+
"""
26+
from typing import List
27+
28+
29+
def increasing_triplet(nums: List[int]) -> bool:
30+
i = j = k = float('inf')
31+
for num in nums:
32+
if num <= i:
33+
i = num
34+
elif num <= j:
35+
j = num
36+
elif num <= k:
37+
return True
38+
return False

0 commit comments

Comments
 (0)