LeetCode: 3sum With Multiplicity Solution

Approach

Create a hash table counting occurences of two sum

Implementation

1/**
2 * @param {number[]} arr
3 * @param {number} target
4 * @return {number}
5 */
6var threeSumMulti = function (arr, target) {
7 const N = arr.length
8 const MOD = 1e9 + 7
9 const map = new Map()
10
11 let res = 0
12
13 for (let i = 0; i < N; i++) {
14 res = (res + (map.get(target - arr[i]) || 0)) % MOD
15
16 for (let j = 0; j < i; j++) {
17 const twoSum = arr[i] + arr[j]
18 map.set(twoSum, (map.get(twoSum) || 0) + 1)
19 }
20 }
21
22 return res
23}

Comments

Loading comments...

Tags

leetcode

hash table

two pointers

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Advantage Shuffle

Mar 25, 2021

Previous Post

HoningJS

Search Posts