3Sum With Multiplicity — LeetCode 923 Python Solution

MediumArrayHash TableTwo PointersCountingSorting
Problem
#923
Reading time
2 min

The problem

Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target. As the answer can be very large, return it modulo 109 + 7.

Example

Input
arr = [1,1,2,2,3,3,4,4,5,5], target = 8
Output
20
Explanation
Enumerating by the values (arr[i], arr[j], arr[k]):

Python solution

Python
class Solution:
    def threeSumMulti(self, arr: List[int], target: int) -> int:
        mod = 10**9 + 7
        cnt = Counter(arr)
        ans = 0
        for j, b in enumerate(arr):
            cnt[b] -= 1
            for a in arr[:j]:
                c = target - a - b
                ans = (ans + cnt[c]) % mod
        return ans

Complexity

MeasureComplexity
TimeO(n^2), where n is the length of the array arr
SpaceO(C), where C is the maximum value of the elements in the array arr, in this problem C = 100 auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 923. 3Sum With Multiplicity is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 923. 3Sum With Multiplicity?
LeetCode 923. 3Sum With Multiplicity is rated Medium on LeetCode.
What is the time complexity of LeetCode 923. 3Sum With Multiplicity?
The Python solution on this page runs in O(n^2), where n is the length of the array arr.
What is the space complexity of LeetCode 923. 3Sum With Multiplicity?
The Python solution on this page uses O(C), where C is the maximum value of the elements in the array arr, in this problem C = 100 auxiliary space.
What topics does LeetCode 923. 3Sum With Multiplicity cover?
LeetCode 923. 3Sum With Multiplicity is tagged Array, Hash Table, Two Pointers, Counting and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview