#611
Valid Triangle Number
MediumArrayTwo PointersBinary SearchGreedySortingTwo PointersSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n³) | O(n²) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
By sorting the array first, we can use a two-pointer technique to efficiently count valid triplets. This reduces the number of checks needed by leveraging the properties of sorted arrays.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array in non-decreasing order.
- 2Step 2: Iterate through the array with index 'k' starting from the third element.
- 3Step 3: For each 'k', use two pointers 'i' (starting from 0) and 'j' (starting from k-1) to find valid pairs (i, j) such that nums[i] + nums[j] > nums[k].
- 4Step 4: If a valid pair is found, all elements between 'i' and 'j' can form valid triangles with nums[k]. Increment the count accordingly and move the pointer 'i' forward.
solution.py13 lines
1def triangleNumber(nums):
2 nums.sort()
3 count = 0
4 n = len(nums)
5 for k in range(2, n):
6 i, j = 0, k - 1
7 while i < j:
8 if nums[i] + nums[j] > nums[k]:
9 count += (j - i)
10 j -= 1
11 else:
12 i += 1
13 return countℹ
Complexity note: The time complexity is O(n²) due to the two-pointer technique inside a single loop, while the sorting step is O(n log n). The space complexity is O(1) as we are using a constant amount of extra space.
- 1Sorting helps reduce the number of checks needed.
- 2Using two pointers can significantly improve efficiency.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.