Valid Triangle Number - Problem

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.

Triangle Validity Rule: For three sides a, b, and c to form a valid triangle, they must satisfy: a + b > c, a + c > b, and b + c > a.

Note: The triangle inequality states that the sum of any two sides must be greater than the third side for all three combinations.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,2,3,4]
Output: 3
💡 Note: Valid triangles are: (2,2,3) since 2+2=4>3, 2+3=5>2, 2+3=5>2; (2,3,4) since 2+3=5>4, 2+4=6>3, 3+4=7>2; (2,3,4) with the other 2. Total: 3 triangles.
Example 2 — No Valid Triangles
$ Input: nums = [1,2,3]
Output: 0
💡 Note: The only triplet is (1,2,3). Check: 1+2=3, which is not greater than 3, so this cannot form a triangle.
Example 3 — All Valid
$ Input: nums = [4,2,3,4]
Output: 4
💡 Note: After sorting [2,3,4,4]: (2,3,4), (2,4,4), (3,4,4), (2,4,4) - all satisfy triangle inequality. Total: 4 triangles.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Valid Triangle Number INPUT nums = [2, 2, 3, 4] 2 idx 0 2 idx 1 3 idx 2 4 idx 3 Triangle Condition: a + b > c a + c > b b + c > a a b c ALGORITHM STEPS 1 Sort Array [2,2,3,4] (already sorted) 2 Fix largest side (k) Iterate k from n-1 to 2 3 Two Pointer Search i=0, j=k-1, find a+b > c 4 Count Triplets If valid, add (j-i) to count Valid Triplets Found: (2,2,3): 2+2=4 > 3 OK (2,3,4): 2+3=5 > 4 OK (2,3,4): 2+3=5 > 4 OK Total Count: 3 FINAL RESULT 3 Valid Triangles (2,2,3) (2,3,4) (2,3,4) Output: 3 Verified: 3 triplets form triangles Key Insight: After sorting, only check a + b > c (where c is largest). The other two conditions are automatically satisfied. Two-pointer technique reduces complexity from O(n^3) to O(n^2). TutorialsPoint - Valid Triangle Number | Optimal Solution (Two Pointers)
Asked in
Amazon 25 Microsoft 18 Google 15 Apple 12
82.0K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen