Valid Triangle Number
Real-world version: Bracing Strut TriplesThe statement here is our own: the same inputs, outputs and technique.
A workshop has a pile of steel struts; nums[i] is the length of the strut in slot i, and a length of 0 marks a slot holding an offcut that is too short to use. The struts arrive in no particular order.
Three struts can be bolted into a rigid triangular brace exactly when each of their lengths is strictly less than the sum of the other two, which is what gives the brace a positive area. A flat, collapsed arrangement does not count.
Count the triples of slots (i, j, k) with i < j < k whose three struts form a rigid brace. Struts of equal length in different slots are different struts, so each triple of slots is counted separately.
Examples
Example 1
- Input
- nums = [6, 3, 4, 6]
- Output
- 4
All four triples of slots qualify: 6, 3, 4 has every length under the sum of the other two, and so do 6, 3, 6 and 6, 4, 6 and 3, 4, 6.
Example 2
- Input
- nums = [2, 3, 5]
- Output
- 0
The only triple has 2 + 3 equal to 5, so the arrangement is flat rather than rigid and nothing is counted.
Example 3
- Input
- nums = [0, 1, 1]
- Output
- 0
Slot 0 holds an offcut of length 0, and 0 + 1 does not exceed 1, so the only triple fails.
Constraints
- 1 <= nums.length <= 1000
- 0 <= nums[i] <= 1000
- With at most 1000 struts the count never exceeds 166167000.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def triangle_number(nums: list[int]) -> int:public int triangleNumber(int[] nums)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 13 test cases: 13 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Earliest Finish Time for Land and Water Rides IReal-world version: Forge and Kiln BookingEasy
- Earliest Finish Time for Land and Water Rides IIReal-world version: Pair of Workshop SlotsMedium
- Path Existence Queries in a Graph IIReal-world version: Relay Hops Across The Field NetworkHard
- Intersection of Two ArraysReal-world version: Shared Scan CodesEasy