Skip to content
Problem 611 · LeetCode 611(opens in a new tab)

Valid Triangle Number

MediumArrays

You are given nums, a list of non-negative whole numbers. Think of each number as the length of a stick.

Count how many ways you can choose three different positions so that their three lengths can form a triangle. Positions matter: equal lengths at different positions are different choices. Three lengths form a triangle when any two of them add up to strictly more than the third.

Example 1

Input:  nums = [2, 3, 4, 7, 5]
Output: 5
Why:    2,3,4  2,4,5  3,4,5  3,5,7  4,5,7 (2 + 5 = 7 is flat)
2 more examples and the constraints

Example 2

Input:  nums = [1, 1, 1, 0]
Output: 1
Why:    only 1,1,1; a side of 0 never works

Example 3

Input:  nums = [5, 10]
Output: 0
Why:    fewer than three sticks

Constraints

  • 1 ≤ length of nums ≤ 1,000
  • 0 ≤ nums[i] ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every tripleO(n³)
  2. Sort, fix the longest side, two pointersO(n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 numbersVerdict
Try every tripleO(n³)
About 166 million checks
Sort, then binary searchO(n² log n)
Passes; a search per pair
Sort, fix the longest side, two pointersO(n²)
Best; one sweep per longest side

n = length of nums.

Edge cases to test

  • Fewer than three numbers. No triple exists, so the answer is 0.
  • Zeros. A side of 0 can never make a triangle; the strict comparison rejects it.
  • Flat triples. Like 2, 3, 5: the sum equals the longest side, so it does not count.
  • All equal. Every triple is a triangle, so the answer is n choose 3.

Common mistakes

  • Using >= instead of >, which counts flat triples.
  • Removing duplicate lengths; triples are counted by position, so equal values still count separately.
  • Fixing the smallest side instead of the largest, which breaks the one-way pointer moves.

How to talk through it

  1. 1Clarify. Are triples counted by position? Can lengths be 0? Does a flat triple count?
  2. 2Simplify the test. Once sorted, only one check matters: the two short sides must beat the longest.
  3. 3Give the triple loop. O(n³) is too slow for 1,000; sorting plus binary search gets O(n² log n).
  4. 4Two pointers. Fix the longest side; when i and j work, all of i..j−1 work, so count j − i at once.
  5. 5Test out loud. Try fewer than three numbers, zeros, a flat triple and all-equal lengths.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?