MediumNo. 0454
4Sum II — LeetCode 454 Python Solution
- Pattern
- Hash Map
- Topics
- Array, Hash Table
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: 0 <= i, j, k, l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
This statement is abridged. Read the full problem on LeetCode.
Example
- Input
- nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
- Output
- 2
- Explanation
- The two tuples are:
Python solution
class Solution:
def fourSumCount(
self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]
) -> int:
cnt = Counter(a + b for a in nums1 for b in nums2)
return sum(cnt[-(c + d)] for c in nums3 for d in nums4)Complexity
- Time
- O(n2)
- Space · auxiliary
- O(n2)where n is the length of the array
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 454. 4Sum II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0457 | Circular Array Loop | Medium |
| 0448 | Find All Numbers Disappeared in an Array | Easy |
| 0447 | Number of Boomerangs | Medium |
| 0001 | Two Sum | Easy |
| 0036 | Valid Sudoku | Medium |
| 0037 | Sudoku Solver | Hard |
Frequently asked questions
- How hard is LeetCode 454. 4Sum II?
LeetCode 454. 4Sum II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 454. 4Sum II?
The Python solution on this page runs in O(n2).
- What is the space complexity of LeetCode 454. 4Sum II?
The Python solution on this page uses O(n2), where n is the length of the array auxiliary space.
- What topics does LeetCode 454. 4Sum II cover?
LeetCode 454. 4Sum II is tagged Array and Hash Table on LeetCode.