Skip to content

611. Valid Triangle Number

MediumLeetCode

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

How to solve the problem

  • Two Pointers
  • Brute Force (Time Limit Exceeded)
python
# Approach 1: Two Pointers
class Solution:
    def triangleNumber(self, nums: List[int]) -> int:
        n = len(nums)
        nums.sort()
        result = 0
        for k in range(2, n):  # k is the longest side starting from the third element in nums
            left = 0
            right = k - 1
            while left < right:
                if nums[left] + nums[right] > nums[k]:
                    result += right - left # all the left to right are available
                    right -= 1
                else:
                    left += 1
        return result
python
# Approach 2: Brute Force (Time Limit Exceeded)
class Solution:
    def triangleNumber(self, nums: List[int]) -> int:
        n = len(nums)
        result = 0
        nums.sort()
        for i in range(n):
            for j in range(i + 1, n):
                for k in range(j + 1, n):
                    if nums[i] + nums[j] > nums[k]:
                        result += 1
                        continue
        return result

Complexity

  • Approach 1 (Two Pointers): Time complexity: O(n²), Space complexity: O(1)
  • Approach 2 (Brute Force): Time complexity: O(n³), Space complexity: O(1)

Comments

No comments yet. Be the first to comment!