bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 18. 4Sum

18. 4Sum

Leetcode Solutions

Two Pointers Approach forSum

  1. Sort the input array nums.
  2. Initialize an empty list res to store the quadruplets.
  3. Iterate over the array with index i from 0 to len(nums) - 3:
    • If i is greater than 0 and nums[i] is the same as nums[i - 1], skip to avoid duplicates.
    • Iterate over the array with index j from i + 1 to len(nums) - 2:
      • If j is greater than i + 1 and nums[j] is the same as nums[j - 1], skip to avoid duplicates.
      • Set two pointers, left = j + 1 and right = len(nums) - 1.
      • While left < right:
        • Calculate the sum s = nums[i] + nums[j] + nums[left] + nums[right].
        • If s is less than target, increment left.
        • If s is greater than target, decrement right.
        • If s equals target, add [nums[i], nums[j], nums[left], nums[right]] to res, then:
          • Increment left while nums[left] is the same as nums[left - 1].
          • Decrement right while nums[right] is the same as nums[right + 1].
  4. Return the list res containing all unique quadruplets.
UML Thumbnail

Hash Set Approach forSum

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...