Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Valid Triangle Number
Bookmark
Input
Standard
Larger
Small
Custom
nums
=
[2, 2, 3, 4]
0
1
2
3
2
2
3
4
count = 0
sides a ≤ b ≤ c form a triangle only if a + b > c
0
1
2
3
2
2
3
4
count = 0
sides a ≤ b ≤ c form a triangle only if a + b > c
0
1
2
3
2
2
3
4
k
count = 0
fix the largest side c = nums[3] =
4
0
1
2
3
2
2
3
4
k
left
right
count = 0
pick the two smaller sides: left = 0, right = 2
0
1
2
3
2
2
3
4
k
left
right
a=2
b=3
c=4
count = 2
+2
every left in [0..1] also works →
+2
(count 0 → 2)
0
1
2
3
2
2
3
4
k
left
right
a=2
b=3
c=4
count = 2
shrink the window: right = 1
0
1
2
3
2
2
3
4
k
left
right
✕
a=2
b=2
c=4
a + b too short to close
count = 2
sum too small, need a bigger a: left = 1
0
1
2
3
2
2
3
4
k
left
right
count = 2
fix the largest side c = nums[2] =
3
0
1
2
3
2
2
3
4
k
left
right
a=2
b=2
c=3
count = 2
2 + 2 =
4
>
3
0
1
2
3
2
2
3
4
k
left
right
a=2
b=2
c=3
count = 3
+1
every left in [0..0] also works →
+1
(count 2 → 3)
0
1
2
3
2
2
3
4
3 valid triangles
total:
3 valid triangles
algo
master
.
io
Step:
Count triangles with sort + two pointers
0 / 14
Input
Standard
Larger
Small
Custom
nums
=
[2, 2, 3, 4]
0 / 14
algo
master
.
io
Step:
Count triangles with sort + two pointers