Valid Triangle Number
Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
Examples
Valid combinations are:
- 2,3,4 (using the first 2)
- 2,3,4 (using the second 2)
- 2,2,3
Valid combinations are:
- 2,3,4 (first 4)
- 2,3,4 (second 4)
- 2,4,4
- 3,4,4
Problem Understanding
We need to find triplets (a, b, c) such that they can form a valid triangle.
Triangle Inequality Theorem:
For three lengths to form a triangle, the sum of any two sides must be greater than the third side:
a + b > ca + c > bb + c > a
Simplification:
If we sort the numbers such that a <= b <= c, we strictly know that a + c > b and b + c > a (since c is the largest). The only condition we need to check is:
a + b > c
Algorithm Strategy
This problem is a variation of 3-Sum. We fix the longest side c (let's say nums[k]) and try to find two smaller sides a (nums[i]) and b (nums[j]) such that nums[i] + nums[j] > nums[k].
Algorithm:
- Sort the array in non-decreasing order.
- Iterate
kfrom the end (n-1down to2). This sets our longest sidec. - Initialize
i = 0andj = k - 1. - Two Pointer Check:
- If
nums[i] + nums[j] > nums[k]: Valid! Since the array is sorted, every number fromnums[i]tonums[j-1]summed withnums[j]will ALSO be greater thannums[k]. This gives usj - ivalid triangles. We count them and movejleft (j--) to look for more. - If
nums[i] + nums[j] <= nums[k]: The sum is too small. We need a larger smallest side, so we moveiright (i++).
- If
Interactive Visualization
Sorted: [2, 2, 3, 4]. Fix k=3 (val 4). i=0 (val 2), j=2 (val 3). Check: 2 + 3 > 4? YES (5 > 4).
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run: nums = [2, 2, 3, 4] (Sorted)
- Edge Cases & Common Mistakes
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
