Created
January 2, 2026 08:24
-
-
Save rtsoy/b91df4ea475b2f5b0e13b4ae0d504fa0 to your computer and use it in GitHub Desktop.
18. 4Sum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://leetcode.com/problems/4sum/ | |
| // | |
| // Time: O(n^3) | |
| // Space: O(1) | |
| // | |
| // n = number of elements in array | |
| // .................... // | |
| func fourSum(nums []int, target int) [][]int { | |
| n := len(nums) | |
| sort.Ints(nums) | |
| res := make([][]int, 0) | |
| for i := 0; i < n; i++ { | |
| if i > 0 && nums[i] == nums[i-1] { | |
| continue | |
| } | |
| for j := i+1; j < n; j++ { | |
| if j > i+1 && nums[j] == nums[j-1] { | |
| continue | |
| } | |
| l, r := j+1, n-1 | |
| for l < r { | |
| sum := nums[i] + nums[j] + nums[l] + nums[r] | |
| if sum == target { | |
| res = append(res, []int{ | |
| nums[i], nums[j], | |
| nums[l], nums[r], | |
| }) | |
| l++ | |
| r-- | |
| for l < r && nums[l] == nums[l-1] { | |
| l++ | |
| } | |
| for l < r && nums[r] == nums[r+1] { | |
| r-- | |
| } | |
| } else if sum > target { | |
| r-- | |
| } else { | |
| l++ | |
| } | |
| } | |
| } | |
| } | |
| return res | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment