Sponsored
Sponsored
First, sort the array. Then, iterate through the array by selecting the third side of the triplet. Use a two-pointer technique to find valid pairs for the first and second sides. For each third side, initialize two pointers, one starting at the beginning of the list and the other just before the third side. Check the sum of the elements at the two pointers and compare it to the third side. If they form a valid triangle, move the inner pointer inward; otherwise, adjust the pointers accordingly.
Time Complexity: O(n^2), where n is the length of the input array because the main operations involve sorting and a nested loop.
Space Complexity: O(1) since it uses only a fixed amount of extra space.
1class Solution:
2 def triangleNumber(self, nums):
3 nums.sort()
4 count = 0
5 for i in range(len(nums) - 1, 1, -1):
6 left, right = 0, i - 1
7 while left < right:
8 if nums[left] + nums[right] > nums[i]:
9 count += right - left
10 right -= 1
11 else:
12 left += 1
13 return count
14
15# Example usage:
16sol = Solution()
17print(sol.triangleNumber([2, 2, 3, 4]))
This Python solution sorts the list and uses two pointers, similar to other languages, to efficiently count the number of triplets satisfying triangle conditions.
This approach involves checking every possible triplet from the array to see if they can form a triangle by comparing their sums directly. This solution is straightforward but less efficient since it considers all combinations without optimizations such as sorting or double pointers.
Time Complexity: O(n^3), as it checks every combination of three numbers in the array.
Space Complexity: O(1), requiring minimal additional storage.
1
This straightforward Java implementation bruteforces through each triplet of numbers, verifying if they can form a triangle.