KatInterview

611. Valid Triangle Number

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the number of triplets in a given array nums that can form the sides of a valid triangle. According to the triangle inequality theorem, three segments of lengths a, b, and c can form a triangle if and only if the sum of the lengths of any two sides is greater than the length of the third side. That is, we must satisfy all three conditions: a + b > c, a + c > b, and b + c > a. A side length cannot be zero or negative; however, the input array can contain zeros. These must be handled correctly.

Solution

Valid Triangle Number in Python

class Solution:
    def triangleNumber(self, nums: list[int]) -> int:
        n = len(nums)
        if n < 3:
            return 0

        # Sort the array to simplify the triangle inequality check.
        # After sorting, if we have a <= b <= c, we only need to check a + b > c.
        nums.sort()

        count = 0
        # Iterate from the end of the array, fixing the largest side 'c'.
        for k in range(n - 1, 1, -1):
            # Let nums[k] be the side 'c'.
            # We need to find pairs (nums[left], nums[right]) in the subarray nums[0...k-1]
            # such that nums[left] + nums[right] > nums[k].
            left, right = 0, k - 1
            while left < right:
                # If the sum of the two smaller sides is greater than the largest side
                if nums[left] + nums[right] > nums[k]:
                    # All elements from nums[left] to nums[right-1] paired with nums[right]
                    # will also form a valid triangle.
                    # There are 'right - left' such pairs.
                    count += (right - left)
                    # Try a smaller 'b' to find more triangles.
                    right -= 1
                else:
                    # The sum is too small, we need a larger 'a'.
                    left += 1
        
        return count

Valid Triangle Number in Java

import java.util.Arrays;

class Solution {
    public int triangleNumber(int[] nums) {
        int n = nums.length;
        if (n < 3) {
            return 0;
        }

        // Sort the array to simplify the triangle inequality check.
        // After sorting, if we have a <= b <= c, we only need to check a + b > c.
        Arrays.sort(nums);

        int count = 0;
        // Iterate from the end of the array, fixing the largest side 'c'.
        for (int k = n - 1; k >= 2; k--) {
            // Let nums[k] be the side 'c'.
            // We need to find pairs (nums[left], nums[right]) in the subarray nums[0...k-1]
            // such that nums[left] + nums[right] > nums[k].
            int left = 0, right = k - 1;
            while (left < right) {
                // If the sum of the two smaller sides is greater than the largest side
                if (nums[left] + nums[right] > nums[k]) {
                    // All elements from nums[left] to nums[right-1] paired with nums[right]
                    // will also form a valid triangle.
                    // There are 'right - left' such pairs.
                    count += (right - left);
                    // Try a smaller 'b' to find more triangles.
                    right--;
                } else {
                    // The sum is too small, we need a larger 'a'.
                    left++;
                }
            }
        }

        return count;
    }
}

Valid Triangle Number in C++

class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        int n = nums.size();
        if (n < 3) {
            return 0;
        }

        // Sort the array to simplify the triangle inequality check.
        // After sorting, if we have a <= b <= c, we only need to check a + b > c.
        sort(nums.begin(), nums.end());

        int count = 0;
        // Iterate from the end of the array, fixing the largest side 'c'.
        for (int k = n - 1; k >= 2; --k) {
            // Let nums[k] be the side 'c'.
            // We need to find pairs (nums[left], nums[right]) in the subarray nums[0...k-1]
            // such that nums[left] + nums[right] > nums[k].
            int left = 0, right = k - 1;
            while (left < right) {
                // If the sum of the two smaller sides is greater than the largest side
                if (nums[left] + nums[right] > nums[k]) {
                    // All elements from nums[left] to nums[right-1] paired with nums[right]
                    // will also form a valid triangle.
                    // There are 'right - left' such pairs.
                    count += (right - left);
                    // Try a smaller 'b' to find more triangles.
                    right--;
                } else {
                    // The sum is too small, we need a larger 'a'.
                    left++;
                }
            }
        }

        return count;
    }
};

Valid Triangle Number in TypeScript

function triangleNumber(nums: number[]): number {
    const n = nums.length;
    if (n < 3) {
        return 0;
    }

    // Sort the array to simplify the triangle inequality check.
    // After sorting, if we have a <= b <= c, we only need to check a + b > c.
    nums.sort((a, b) => a - b);

    let count = 0;
    // Iterate from the end of the array, fixing the largest side 'c'.
    for (let k = n - 1; k >= 2; k--) {
        // Let nums[k] be the side 'c'.
        // We need to find pairs (nums[left], nums[right]) in the subarray nums[0...k-1]
        // such that nums[left] + nums[right] > nums[k].
        let left = 0, right = k - 1;
        while (left < right) {
            // If the sum of the two smaller sides is greater than the largest side
            if (nums[left] + nums[right] > nums[k]) {
                // All elements from nums[left] to nums[right-1] paired with nums[right]
                // will also form a valid triangle.
                // There are 'right - left' such pairs.
                count += (right - left);
                // Try a smaller 'b' to find more triangles.
                right--;
            } else {
                // The sum is too small, we need a larger 'a'.
                left++;
            }
        }
    }

    return count;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.