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: Count Triangles from [2,2,3,4]2234Triangle Check: 2 + 2 = 4 > 3 ✓223Valid triangles: (2,2,3), (2,3,4), (2,3,4)Output: 3
Understanding the Visualization
1
Input Array
Array of potential triangle side lengths
2
Triangle Check
Apply triangle inequality: sum of any two sides > third side
3
Count Result
Return total number of valid triangle triplets
Key Takeaway
🎯 Key Insight: After sorting, we only need to check if the sum of two smaller sides exceeds the largest side
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