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
Explanation: Valid combinations are three 4,3,4 and one 2,3,4.
Constraints:
To solve this problem efficiently, we use the fact that for any three sides to form a triangle, the sum of any two sides must be greater than the third side. We particularly leverage the sorted order of the array to reduce the number of comparisons:
nums[i] + nums[j] > nums[k]
more easily.O(n^3)
complexity, optimize it by leveraging the sorted nature:
O(n^2)
.def triangleNumber(nums):
nums.sort()
count = 0
n = len(nums)
for i in range(n-2):
k = i + 2
for j in range(i+1, n-1):
while k < n and nums[i] + nums[j] > nums[k]:
k += 1
count += k - j - 1
return count
O(n log n)
where n
is the number of elements in nums
.O(n^2)
, and the innermost while-loop runs in constant time on average over all iterations.O(n^2)
, which is efficient for the given constraints (n <= 1000
).This solution ensures that we consider only those side lengths that can actually form a triangle by sorting and strategically using the triangle inequality rule.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?