Valid Triangle Number Problem
Description
LeetCode Problem 611.
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.
Example 1:
Input: nums = [2,2,3,4]
Output: 3
Explanation: Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
Example 2:
Input: nums = [4,2,3,4]
Output: 4
Constraints:
- 1 <= nums.length <= 1000
- 0 <= nums[i] <= 1000
Solution
Approach: Sort, Then Two Pointers for Each Longest Side
Checking every triplet takes O(n3). Sorting first lets us count many triplets at once.
Three lengths a ≤ b ≤ c form a triangle exactly when a + b > c: the other two inequalities hold automatically because c is the largest. So sort nums, and for each index longest (from the right end down to 2), count the pairs low < high < longest with nums[low] + nums[high] > nums[longest]:
- Start with
low = 0andhigh = longest - 1. - If
nums[low] + nums[high] > nums[longest], then every index fromlowtohigh - 1also works withhigh, since those values are at leastnums[low]. Addhigh - lowand movehighleft. - Otherwise
nums[low]is too short even with the largest partner left, so movelowright. - Stop when the pointers meet.
Each step moves one pointer, so one value of longest costs O(n).
For [2, 2, 3, 4] and longest side 4: 2 + 3 > 4 with low = 0, high = 2 adds 2 (both 2s pair with 3); then 2 + 2 > 4 fails. With longest side 3: 2 + 2 > 3 adds 1. Total 3.
Zeros need no special case: a side of length 0 never satisfies a + b > c with the other two, so it is never counted.
Complexity: O(n2) time and O(1) extra space apart from the sort, where n is the length of nums.
class Solution:
def triangleNumber(self, nums: List[int]) -> int:
nums.sort()
count = 0
# Fix the longest side nums[longest]; find pairs to its left whose sum is bigger.
for longest in range(len(nums) - 1, 1, -1):
low, high = 0, longest - 1
while low < high:
if nums[low] + nums[high] > nums[longest]:
# Every index from low to high - 1 also works with high.
count += high - low
high -= 1
else:
low += 1 # nums[low] is too short even with the biggest partner
return count