Valid Triangle Number (LeetCode 611): Solution and Explanation
Count how many triplets of array values could be the three side lengths of a real triangle, where each triplet uses three different indices.
Intuition
Three sticks close into a triangle when each pair outreaches the third. That is three inequalities, but once the sticks are sorted as a <= b <= c, two of them always hold. Only a + b > c can fail.
So sort the array and fix the longest side c = nums[k]. Now the question is how many pairs i < j < k have nums[i] + nums[j] > c.
Put i at the shortest stick and j just below k. If nums[i] + nums[j] > c, then every stick between i and j - 1 is at least as long as nums[i], so all of them also work with j. That is j - i triangles in one step, and j can move down. If the sum is too short, nums[i] cannot work with any remaining j, so i moves up.
Each step moves one pointer, so one value of k costs O(k) and the whole sweep costs O(n^2).
Approach: Sort, fix the longest side, two pointers
- Sort
numsin ascending order and setcount = 0. - For
kfrom the last index down to 2, seti = 0andj = k - 1. - While
i < j: ifnums[i] + nums[j] > nums[k], addj - itocountand decrementj. - Otherwise increment
i. - Return
count.
Step-by-step example
nums = [2,2,3,4]
- Sorted, the sticks are [2,2,3,4].
- k = 3, c = 4. i = 0, j = 2: 2 + 3 = 5 > 4, so both i = 0 and i = 1 pair with j = 2. count = 2, j becomes 1.
- i = 0, j = 1: 2 + 2 = 4 is not > 4, so i becomes 1 and the loop ends.
- k = 2, c = 3. i = 0, j = 1: 2 + 2 = 4 > 3, so count = 3 and j becomes 0.
- No k is left. The answer is 3.
Code: Python, Java, C++
1class Solution:
2 def triangleNumber(self, nums: List[int]) -> int:
3 nums.sort()
4 count = 0
5 for k in range(len(nums) - 1, 1, -1):
6 i, j = 0, k - 1
7 while i < j:
8 if nums[i] + nums[j] > nums[k]:
9 count += j - i
10 j -= 1
11 else:
12 i += 1
13 return count1class Solution {
2 public int triangleNumber(int[] nums) {
3 Arrays.sort(nums);
4 int count = 0;
5 for (int k = nums.length - 1; k >= 2; k--) {
6 int i = 0, j = k - 1;
7 while (i < j) {
8 if (nums[i] + nums[j] > nums[k]) {
9 count += j - i;
10 j--;
11 } else {
12 i++;
13 }
14 }
15 }
16 return count;
17 }
18}1class Solution {
2public:
3 int triangleNumber(vector<int>& nums) {
4 sort(nums.begin(), nums.end());
5 int count = 0;
6 for (int k = (int)nums.size() - 1; k >= 2; k--) {
7 int i = 0, j = k - 1;
8 while (i < j) {
9 if (nums[i] + nums[j] > nums[k]) {
10 count += j - i;
11 j--;
12 } else {
13 i++;
14 }
15 }
16 }
17 return count;
18 }
19};Time and space complexity
O(n^2)
Sorting is O(n log n). For each k the two pointers meet after at most k moves, which sums to O(n^2).
O(1)
Only a few indices and the count, apart from the space the sort uses.
Other approaches
Sort and binary search (time O(n^2 log n), space O(1))
Fix the two shorter sides i < j and binary search for the first index k whose value is at least nums[i] + nums[j]. Every index between j + 1 and that point is a valid third side.
Brute force (time O(n^3), space O(1))
Try every triplet and test all three triangle inequalities. Simple, but about 1.7 * 10^8 triplets at n = 1000.
Common mistakes
- Forgetting to sort. Without order, the single check a + b > c is not enough.
- Adding 1 instead of j - i when the sum is large enough, which misses the pairs between i and j.
- Treating zeros specially. A zero side never satisfies a + b > c with b <= c, so the main loop already excludes it.
- Moving the wrong pointer. When the sum is too small, only a longer short side can help, so i moves up.
Frequently asked questions
Why fix the longest side instead of the shortest?
With the longest side fixed, a successful sum tells you about a whole block of pairs at once. Fixing the shortest side does not give that monotonic structure, so the two pointers would not know which way to move.
Do equal values count as different triplets?
Yes. Triplets are chosen by index, so two sticks of the same length at different positions give different triplets. In [2,2,3,4], (2,3,4) is counted twice.
Why is this problem listed under binary search?
A common solution fixes two sides and binary searches for how far the third side can go. The two pointer sweep shown here is the faster version of the same idea.