> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Valid Triangle Number Python Solution

> Tested Python solution for LeetCode 611 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 611, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Two Pointers](/catalog/topics/two-pointers), [Binary Search](/catalog/topics/binary-search), [Greedy](/catalog/topics/greedy), [Sorting](/catalog/topics/sorting). [View on LeetCode](https://leetcode.com/problems/valid-triangle-number/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 611   # by problem number
lcpy gen -s valid_triangle_number   # by problem name
```

## 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.

### Examples

```
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
```

```
Input: nums = [4,2,3,4]
Output: 4
```

### Constraints

* 1 \<= nums.length \<= 1000
* 0 \<= nums\[i] \<= 1000

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/valid_triangle_number/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/valid_triangle_number/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n^2)
    # Space: O(1) extra (sorting not counted)
    def triangle_number(self, nums: list[int]) -> int:
        nums = sorted(nums)
        count = 0
        for k in range(len(nums) - 1, 1, -1):
            left, right = 0, k - 1
            while left < right:
                if nums[left] + nums[right] > nums[k]:
                    count += right - left
                    right -= 1
                else:
                    left += 1
        return count
```

## Complexity

| Time | Space |
| - | - |
| O(n^2) | O(1) extra (sorting not counted) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.