|
| 1 | +# Valid Triangle Number (Medium) |
| 2 | + |
| 3 | +**Problem ID:** 611 |
| 4 | +**Date:** 2025-09-26 |
| 5 | +**Link:** https://leetcode.com/problems/valid-triangle-number/ |
| 6 | + |
| 7 | +## Approach |
| 8 | + |
| 9 | +To solve the "Valid Triangle Number" problem, we can utilize a combination of sorting and the two-pointer technique. The main idea is based on the triangle inequality theorem, which states that for three sides to form a triangle, the sum of the lengths of any two sides must be greater than the length of the third side. |
| 10 | + |
| 11 | +### Approach: |
| 12 | + |
| 13 | +1. **Sorting the Array**: Start by sorting the input array `nums`. This allows us to easily apply the triangle inequality conditions since for any triplet `(a, b, c)` where `a <= b <= c`, it suffices to check if `a + b > c`. |
| 14 | + |
| 15 | +2. **Iterating Through Triplets**: Use a loop to fix the largest side of the triangle (let’s call it `c`) starting from the third element and moving towards the end of the sorted array. For each fixed `c`, we will find pairs `(a, b)` such that `a + b > c`. |
| 16 | + |
| 17 | +3. **Two-Pointer Technique**: |
| 18 | + - Initialize two pointers: one (`left`) starting from the beginning of the array and the other (`right`) just before the current `c`. |
| 19 | + - Check if the sum of the elements at these two pointers (`nums[left] + nums[right]`) is greater than `nums[c]`. If it is, then all pairs from `left` to `right` with the current `right` are valid, since the array is sorted and any element between `left` and `right` will also satisfy the condition. Count these pairs and decrement `right`. |
| 20 | + - If the sum is not greater, increment `left` to try a larger sum. |
| 21 | + |
| 22 | +4. **Counting Valid Triplets**: Keep a cumulative count of valid triplet combinations as you iterate through the array. |
| 23 | + |
| 24 | +### Data Structures: |
| 25 | +- A sorted array to facilitate the two-pointer approach. |
| 26 | +- Simple integer counters to keep track of valid triplet counts. |
| 27 | + |
| 28 | +### Complexity: |
| 29 | +- **Time Complexity**: The sorting step takes \(O(n \log n)\), and the two-pointer traversal for each element takes \(O(n)\). Thus, the overall time complexity is \(O(n^2)\). |
| 30 | +- **Space Complexity**: The space complexity is \(O(1)\) if we ignore the input storage, as we are using only a constant amount of extra space. |
| 31 | + |
| 32 | +This approach efficiently counts the number of valid triangle triplets in the array, leveraging sorting and the two-pointer technique to minimize unnecessary checks. |
0 commit comments