LeetCode 0611. Valid Triangle Number Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0611. Valid Triangle Number

Description

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

Solutions

Solution 1: Sorting + Binary Search

A valid triangle must satisfy: the sum of any two sides is greater than the third side. That is:

$a + b \gt c \tag{1}$

$a + c \gt b \tag{2}$

$b + c \gt a \tag{3}$

If we arrange the sides in ascending order, i.e., a ≤ b ≤ c, then obviously conditions (2) and (3) are satisfied. We only need to ensure that condition (1) is also satisfied to form a valid triangle.

We enumerate i in the range [0, n - 3], enumerate j in the range [i + 1, n - 2], and perform binary search in the range [j + 1, n - 1] to find the first index left that is greater than or equal to nums[i] + nums[j]. Then, the values of k in the range [j + 1, left - 1] satisfy the condition, and we add them to the result ans.

The time complexity is O(n^2log n), and the space complexity is O(log n), where n is the length of the array.

PythonJavaC++GoTypeScriptRust
class Solution: def triangleNumber(self, nums: List[int]) -> int: nums.sort() ans, n = 0, len(nums) for i in range(n - 2): for j in range(i + 1, n - 1): k = bisect_left(nums, nums[i] + nums[j], lo=j + 1) - 1 ans += k - j return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !