Valid Triangle Number

Sort, then for each largest side use two pointers to count valid (a, b) pairs.

Medium
Time O(n^2) Space O(1)
LeetCode
3 min read
two-pointers sorting

Problem#

Count triples (i, j, k) from nums that can form a triangle (the sum of any two sides exceeds the third).

Examples#

  • nums = [2,2,3,4]3
  • nums = [4,2,3,4]4

Constraints#

  • 1 <= nums.length <= 1000, 0 <= nums[i] <= 1000.

Approach#

Sort. For each k (largest side index), keep two pointers l = 0, r = k - 1. If nums[l] + nums[r] > nums[k], then every l..r-1 paired with r works (so add r - l); decrement r. Otherwise increment l.

Solution#

Valid Triangle Number
class Solution {
public:
int triangleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size(), ans = 0;
for (int k = n - 1; k >= 2; --k) {
int l = 0, r = k - 1;
while (l < r) {
if (nums[l] + nums[r] > nums[k]) {
ans += r - l;
--r;
} else {
++l;
}
}
}
return ans;
}
};

Editorial#

Once sorted, the triangle inequality reduces to the single condition that the two smaller sides exceed the largest. Two pointers count valid (l, r) pairs for each k in O(n), giving O(n^2) overall — much better than O(n^3) brute force.

Complexity#

  • Time: O(n^2).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.