Valid Triangles Count
Problem
Given an integer array nums, return the number of triplets chosen from the array that can form valid triangles where the sum of any two sides is greater than the third side.
- 1 ≤ nums.length ≤ 1000
- 0 ≤ nums[i] ≤ 1000
Example
nums = [2,2,3,4]3After sorting, nums = [2,2,3,4]. The valid triangles are (2,3,4), (2,3,4), and (2,2,3). The algorithm sorts the array to leverage the property that if nums[left] + nums[right] > nums[largest_index], then all elements between left and right can form valid triangles with nums[largest_index]. The two-pointer approach efficiently counts these without checking every triplet explicitly.
Approach
Straightforward Solution
A brute-force approach checks all triplets (O(n^3)) by verifying the triangle inequality for each. This is too slow for large inputs.
Core Observation
A triangle is valid if the sum of the lengths of any two sides is greater than the third side. Sorting the array allows us to fix the largest side and use two pointers to find pairs that satisfy this condition efficiently.
Path to Optimal
Sorting the array enables a key insight: for a fixed largest side, if nums[left] + nums[right] > nums[largest_index], then all elements between left and right can form valid triangles with nums[largest_index]. Using two pointers, we can count these pairs in O(n^2) time by moving pointers inward based on the sum comparison.
Optimal Approach
Sort the array. Iterate from the end to fix the largest side. Use two pointers (left at start, right just before largest) to find pairs where the sum is greater than the largest side. When the sum condition is met, add all pairs between left and right to the count and move right pointer leftward; otherwise, move left pointer rightward. This approach counts all valid triangles in O(n^2) time.
Time
O(n^2)
Sorting takes O(n log n). The main loop iterates over n elements, and the two-pointer inner loop moves pointers across the array at most n times per iteration, resulting in O(n^2) total time.
Space
O(1)
The algorithm sorts the input in place and uses only a few variables for pointers and counters, requiring constant auxiliary space.
Pattern Spotlight
Two Pointers (Sorted Array Pair Search)
When searching for pairs that satisfy a sum condition relative to a fixed element in a sorted array, use two pointers from opposite ends to efficiently count or find all valid pairs by moving pointers based on the sum comparison.
Solution
| 1 | class Solution: |
| 2 | def triangleNumber(self, nums: list[int]) -> int: |
| 3 | nums.sort() |
| 4 | triangle_count = 0 |
| 5 | |
| 6 | for largest_index in range(len(nums) - 1, 1, -1): |
| 7 | left = 0 |
| 8 | right = largest_index - 1 |
| 9 | |
| 10 | while left < right: |
| 11 | if nums[left] + nums[right] > nums[largest_index]: |
| 12 | triangle_count += right - left |
| 13 | right -= 1 |
| 14 | else: |
| 15 | left += 1 |
| 16 | |
| 17 | return triangle_count |
Step-by-Step Solution
Sort the Input Array to Enable Two-Pointer Strategy
| 3 | nums.sort() |
| 4 | triangle_count = 0 |
Objective
To arrange the array in ascending order so that the triangle inequality can be efficiently checked using two pointers.
Key Insight
Sorting the array is crucial because it allows the algorithm to fix the largest side and then use two pointers to find all pairs that satisfy the triangle condition without redundant checks. The sorted order guarantees that if a pair sum exceeds the largest side, all pairs between the pointers also satisfy the condition.
Interview Quick-Check
Core Logic
Sorting transforms the problem into a structured search where the triangle inequality can be checked efficiently using two pointers.
Common Pitfalls & Bugs
Forgetting to sort leads to incorrect assumptions about pair sums and invalid counting.
Iterate Backwards Fixing the Largest Side and Use Two Pointers to Count Valid Pairs
| 6 | for largest_index in range(len(nums) - 1, 1, -1): |
| 7 | left = 0 |
| 8 | right = largest_index - 1 |
| 10 | while left < right: |
| 11 | if nums[left] + nums[right] > nums[largest_index]: |
| 12 | triangle_count += right - left |
| 13 | right -= 1 |
| 14 | else: |
| 15 | left += 1 |
Objective
To fix the largest side of the triangle and use two pointers to find all pairs that satisfy the triangle inequality with it.
Key Insight
By fixing the largest side at index largest_index and initializing two pointers at the start and just before largest_index, the algorithm checks if the sum of the two pointer elements exceeds the largest side. If so, all elements between left and right form valid triangles with the largest side, allowing a bulk count. Moving pointers inward based on the sum condition efficiently explores all pairs without redundant checks.
Interview Quick-Check
Core Logic
The two-pointer approach leverages the sorted array to count multiple valid pairs at once by moving the right pointer leftward when the sum condition is met, and moving the left pointer rightward otherwise.
State & Boundaries
The loop continues while left < right to ensure pairs are distinct and valid.
Common Pitfalls & Bugs
Incorrect pointer movement or failing to count all pairs between left and right leads to undercounting or overcounting.
Return the Total Count of Valid Triangles
| 17 | return triangle_count |
Objective
To output the total number of valid triangles found after processing all possible largest sides.
Key Insight
After iterating through all possible largest sides and counting valid pairs with two pointers, the accumulated count represents the total number of valid triangles. Returning this final count completes the solution.
Interview Quick-Check
Core Logic
Returning the accumulated count provides the final answer to the problem.
Line Analysis
This solution has 2 Critical lines interviewers watch for.
if nums[left] + nums[right] > nums[largest_index]:
Check if the sum of nums[left] and nums[right] is greater than nums[largest_index].
This comparison is the core algorithmic check that determines whether the current pair with the fixed largest side forms a valid triangle, enabling bulk counting of all pairs between left and right.
triangle_count += right - left
Add the number of valid pairs between left and right to the triangle count.
This line exploits the sorted order to count all valid pairs between left and right in constant time, dramatically reducing the complexity from checking each pair individually.
nums.sort()
Sort the input array in ascending order.
Sorting enables the two-pointer technique by ensuring the array is ordered, which is essential for the triangle inequality checks and efficient pair counting.
for largest_index in range(len(nums) - 1, 1, -1):
Iterate backwards to fix the largest side of the triangle.
Fixing the largest side from the end leverages the sorted order and allows the two-pointer approach to find valid pairs efficiently.
right -= 1
Move the right pointer one step left to check for other pairs.
After counting valid pairs, moving the right pointer inward explores smaller elements to find additional valid pairs.
else:
Move the left pointer one step right if the sum condition is not met.
If the sum is not greater than the largest side, increasing the left pointer moves to a larger value to try to satisfy the triangle inequality.
while left < right:
Loop while left pointer is less than right pointer.
Ensures that pairs are distinct and valid, preventing overlap or invalid indices.
left += 1
Increment the left pointer to explore new pairs.
Advancing the left pointer after a failed sum check is essential to progress the search for valid pairs.
left = 0
Initialize the left pointer at the start of the array.
The left pointer starts at the smallest element to explore pairs with the fixed largest side.
right = largest_index - 1
Initialize the right pointer just before the largest side.
The right pointer starts just before the largest side to find pairs that can form valid triangles with it.
return triangle_count
Return the total count of valid triangles found.
This returns the final result after all pairs and largest sides have been processed, completing the solution.
triangle_count = 0
Initialize the counter for valid triangles to zero.
This variable accumulates the total number of valid triangles found during the iteration.
Test Your Understanding
Why does moving the right pointer leftward after finding a valid pair count all intermediate pairs between left and right?
Because the array is sorted, if nums[left] + nums[right] > nums[largest_index], then all elements between left and right also satisfy the sum condition with nums[largest_index], allowing us to count all pairs between left and right at once.
Related Problems
Two Pointers pattern
Don't just read it. Drill it.
Reconstruct Valid Triangles Count from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Valid Triangles Count drill