Skip to the code
cf.
+25 XP

#117 Triangle-Ready Segment Count

medium

A vector drawing tool has a set of line segments with lengths lengths. Three segments can be joined into a triangle when the two shorter ones together are strictly longer than the longest one.

Write countTriangles(lengths) that returns how many groups of three different segments (three different indexes) can form a triangle. Segments with the same length are still different segments.

Example 1

Input: lengths = [2,2,3,4]
Output: 3

2, 3, 4 works twice (with either 2) and 2, 2, 3 works. 2, 2, 4 doesn't: 2 + 2 is not more than 4.

Example 2

Input: lengths = [1,2,3]
Output: 0

1 + 2 equals 3, which is not strictly longer.

Constraints

  • 0 <= lengths.length <= 1000
  • 0 <= lengths[i] <= 1000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).