Valid Triangle Number

35 min · triangleNumber()

A pile of cut rods can offer millions of three-rod choices, yet some choices collapse flat instead of forming a triangle. You need to count only the sturdy ones.

The array nums holds non-negative side lengths. Count the index triplets i < j < k whose three values can form a non-degenerate triangle — a triangle with positive area rather than three points on one straight line.

For three sorted side lengths a <= b <= c, the deciding rule is strict: a + b > c.

Keep these details straight:

  • Each choice uses three different positions.
  • Different index triplets count separately, even when their side values match.
  • Equality isn't enough: a + b == c makes a flat, degenerate shape.
  • A zero can never belong to a valid triangle under the strict rule.

Constraints

  • 0 <= nums.length <= 1_000
  • 0 <= nums[i] <= 1_000

Hints

Start with three loops

Enumerate every i < j < k, sort those three side lengths, and test whether the two smaller ones add to more than the largest.

Choose the largest side first

Sort the whole array. Fix index k as the largest side, then ask how many pairs to its left have a sum greater than nums[k].

Count a block at once

If nums[left] + nums[right] > nums[k], then every index from left through right - 1 also forms a valid pair with right. Add right - left, then move right inward.

Follow-up

Can you reach O(n²) time by proving when an entire block of pairs is valid, instead of checking those pairs one at a time?

Visible cases

Examples

Example 1

ready
Input
nums = [
  2,
  2,
  3,
  4
]
Expected
3
Why
three index triples are valid; the sides 2, 2, 4 are exactly degenerate

Example 2

ready
Input
nums = [
  0,
  0,
  1,
  1
]
Expected
0
Why
every three-position choice includes a zero, so none can form a triangle

Example 3

ready
Input
nums = [
  3,
  4,
  5
]
Expected
1
Why
the only three positions satisfy 3 + 4 > 5

Interview signal

Asked at

AmazonGoogleApple
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite