Valid Triangle Number - Problem
Imagine you have a collection of sticks with different lengths, and you want to know how many ways you can pick three sticks to form a valid triangle!
Given an integer array nums representing the lengths of sticks, return the number of triplets that can form valid triangles. Remember the triangle inequality theorem: for any triangle with sides a, b, and c, the sum of any two sides must be greater than the third side.
Examples:
- Sides [2, 2, 3] → Valid triangle (2+2 > 3, 2+3 > 2, 2+3 > 2) ✅
- Sides [1, 2, 3] → Invalid triangle (1+2 = 3, not greater than 3) ❌
Your goal is to count all possible combinations of three elements that satisfy the triangle inequality.
Input & Output
example_1.py — Basic Triangle Formation
$
Input:
nums = [2,2,3,4]
›
Output:
3
💡 Note:
Valid triangles are: [2,2,3], [2,3,4], [2,2,4]. Each satisfies the triangle inequality: sum of any two sides > third side.
example_2.py — Single Valid Triangle
$
Input:
nums = [4,2,3,4]
›
Output:
4
💡 Note:
After sorting [2,3,4,4], valid triangles are: [2,3,4], [2,4,4], [3,4,4], [2,4,4]. All combinations where sum of smaller sides exceeds the largest side.
example_3.py — No Valid Triangles
$
Input:
nums = [1,1,2]
›
Output:
0
💡 Note:
The only possible triangle [1,1,2] is invalid because 1+1 = 2, which is not greater than 2. Triangle inequality requires strict inequality.
Visualization
Tap to expand
Understanding the Visualization
1
Sort the Sticks
Arrange all sticks from shortest to longest for systematic checking
2
Pick the Longest
Choose the longest stick as one side of the triangle
3
Two-Pointer Search
Use two pointers to find all valid pairs for the remaining two sides
4
Count Efficiently
When a valid combination is found, count all possibilities at once
Key Takeaway
🎯 Key Insight: Sorting enables efficient triangle counting - when two smaller sides sum exceeds the largest, all intermediate combinations work too!
Time & Space Complexity
Time Complexity
O(n² log n)
O(n log n) for sorting + O(n²) for nested loops * O(log n) for binary search
⚠ Quadratic Growth
Space Complexity
O(1)
Only using a few variables, sorting can be done in-place
✓ Linear Space
Constraints
- 1 ≤ nums.length ≤ 1000
- 0 ≤ nums[i] ≤ 1000
- Triangle inequality: For sides a, b, c, need a+b>c, b+c>a, and a+c>b
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code