LeetCode 0259. 3Sum Smaller Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0259. 3Sum Smaller

Description

Given an array of n integers nums and an integer target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

 

Example 1:

Input: nums = [-2,0,1,3], target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]

Example 2:

Input: nums = [], target = 0
Output: 0

Example 3:

Input: nums = [0], target = 0
Output: 0

 

Constraints:

  • n == nums.length
  • 0 <= n <= 3500
  • -100 <= nums[i] <= 100
  • -100 <= target <= 100
  • The input is generated such that the answer is less than or equal to 109.

Solutions

Solution 1: Sorting + Two Pointers + Enumeration

Since the order of elements does not affect the result, we can sort the array first and then use the two-pointer method to solve this problem.

First, we sort the array and then enumerate the first element nums[i]. Within the range nums[i+1:n-1], we use two pointers pointing to nums[j] and nums[k], where j is the next element of nums[i] and k is the last element of the array.

  • If nums[i] + nums[j] + nums[k] < target, then for any element j \lt k' ≤ k, we have nums[i] + nums[j] + nums[k'] < target. There are k - j such k', and we add k - j to the answer. Next, move j one position to the right and continue to find the next k that meets the condition until j ≥ k.
  • If nums[i] + nums[j] + nums[k]target, then for any element j ≤ j' \lt k, it is impossible to make nums[i] + nums[j'] + nums[k] < target. Therefore, we move k one position to the left and continue to find the next k that meets the condition until j ≥ k.

After enumerating all i, we get the number of triplets that meet the condition.

The time complexity is O(n^2), and the space complexity is O(log n). Here, n is the length of the array nums.

PythonJavaC++GoTypeScriptJavaScript
class Solution: def threeSumSmaller(self, nums: List[int], target: int) -> int: nums.sort() ans, n = 0, len(nums) for i in range(n - 2): j, k = i + 1, n - 1 while j < k: x = nums[i] + nums[j] + nums[k] if x < target: ans += k - j j += 1 else: k -= 1 return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !