Similar Problems
Similar Problems not available
3sum With Multiplicity - Leetcode Solution
Companies:
LeetCode: 3sum With Multiplicity Leetcode Solution
Difficulty: Medium
Topics: hash-table sorting array two-pointers
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.
Example 1:
Input: nums = [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using the first 2) 2,2,3 2,2,4
Solution:
This problem can be solved using a combination of two-pointer technique, sorting and counting. We can first sort the given array and then use two pointers to traverse through the array and count triplets that can form a triangle. To optimize the solution, we can use a hashmap to store the frequency of each element in the array. Here are the detailed steps:
- Sort the given array in non-decreasing order.
- Initialize a hashmap to store the frequency of each element in the array.
- Loop through the sorted array using a pointer i from 0 to n-2, where n is the size of the array.
- Initialize two pointers j and k, where j=i+1 and k=n-1.
- While j < k, check if nums[i] + nums[j] > nums[k]. If yes, we can increment the count of valid triplets by the product of (frequency of nums[i])(frequency of nums[j])(frequency of nums[k]). This is because for each occurrence of nums[i] and nums[j], there will be (frequency of nums[k]) valid triplets that can be formed.
- If nums[i] + nums[j] <= nums[k], we can increment j by 1, else we can decrement k by 1.
- At the end of the loop, return the count of valid triplets.
Here is the Python code for the above solution:
class Solution: def triangleNumber(self, nums: List[int]) -> int: nums.sort() count = 0 n = len(nums) freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
for i in range(n-2):
j = i+1
k = n-1
while j < k:
if nums[i] + nums[j] > nums[k]:
count += freq[nums[i]]*freq[nums[j]]*freq[nums[k]]
k -= 1
else:
j += 1
return count
Time Complexity: O(n^2), where n is the size of the given array. This is because we are using two pointers to traverse through the sorted array.
Space Complexity: O(n), where n is the size of the given array. This is because we are using a hashmap to store the frequency of each element.
3sum With Multiplicity Solution Code
1