Valid Triangle Number — LeetCode 611 Python Solution

MediumGreedyArrayTwo PointersBinary SearchSorting
Problem
#611
Reading time
2 min

The problem

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

Input
nums = [2,2,3,4]
Output
3
Explanation
Valid combinations are:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n^2\log n)
SpaceO(\log n), where n is the length of the array auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 611. Valid Triangle Number is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 611. Valid Triangle Number?
LeetCode 611. Valid Triangle Number is rated Medium on LeetCode.
What is the time complexity of LeetCode 611. Valid Triangle Number?
The Python solution on this page runs in O(n^2\log n).
What is the space complexity of LeetCode 611. Valid Triangle Number?
The Python solution on this page uses O(\log n), where n is the length of the array auxiliary space.
What topics does LeetCode 611. Valid Triangle Number cover?
LeetCode 611. Valid Triangle Number is tagged Greedy, Array, Two Pointers, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview