Skip to content

Commit 635326e

Browse files
committed
Add solution for increasing array triplet
1 parent 5daf3bd commit 635326e

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

array/increasing-triplet/README.md

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# 334. Increasing Triplet Subsequence
2+
3+
## Description
4+
See https://leetcode.com/problems/increasing-triplet-subsequence/description/
5+
6+
## Problem
7+
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 exists, return `false`.
8+
9+
## Example 1
10+
11+
```
12+
Input: nums = [1,2,3,4,5]
13+
Output: true
14+
Explanation: Any triplet where i < j < k is valid.
15+
```
16+
17+
## Example 2
18+
19+
```
20+
Input: nums = [5,4,3,2,1]
21+
Output: false
22+
Explanation: No triplet exists.
23+
```
24+
25+
## Example 3
26+
27+
```
28+
Input: nums = [2,1,5,0,4,6]
29+
Output: true
30+
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
31+
```
32+
33+
## Constraints
34+
35+
```
36+
1 <= nums.length <= 5 * 105
37+
-231 <= nums[i] <= 231 - 1
38+
```
39+
40+
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def increasing_triplet(nums: list[int]) -> bool:
2+
first = second = float("inf")
3+
for n in nums:
4+
if n <= first:
5+
first = n
6+
elif n <= second:
7+
second = n
8+
else:
9+
return True
10+
return False
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from increasingtriplet import increasing_triplet
2+
3+
4+
def test_example_1():
5+
nums = [1, 2, 3, 4, 5]
6+
assert increasing_triplet(nums) == True
7+
8+
9+
def test_example_2():
10+
nums = [5, 4, 3, 2, 1]
11+
assert increasing_triplet(nums) == False
12+
13+
14+
def test_example_3():
15+
nums = [2, 1, 5, 0, 4, 6]
16+
assert increasing_triplet(nums) == True
17+
18+
19+
def test_example_4():
20+
nums = [20, 100, 10, 12, 5, 13]
21+
assert increasing_triplet(nums) == True
22+
23+
24+
def test_example_5():
25+
nums = [2, 2, 3, 3, 2, 2, 2, 3, 1]
26+
assert increasing_triplet(nums) == False

0 commit comments

Comments
 (0)