Skip to content

Instantly share code, notes, and snippets.

@zyxd
Last active May 8, 2023 14:50
Show Gist options
  • Save zyxd/2a88e9526cc4ee19b64295628bac6573 to your computer and use it in GitHub Desktop.
Save zyxd/2a88e9526cc4ee19b64295628bac6573 to your computer and use it in GitHub Desktop.
One of 3Sum (https://leetcode.com/problems/3sum) solution
const unique = (array) => Array.from(
new Set(array.map(x => JSON.stringify(x))),
x => JSON.parse(x)
)
const combinations = (array) => new Array(1 << array.length)
.fill()
.map((_, i) => array.filter((_, j) => i & (1 << j)))
const threeSum = (array) => combinations(array)
.filter((t) => t.length === 3)
.filter(([a, b, c]) => a + b + c === 0)
.map((t) => t.sort())
.map((t) => JSON.stringify(t))
.reduce((a, t) => ([...a, ...(!a.includes(t) ? [t] : [])]), [])
.map((t) => JSON.parse(t))
threeSum([-1, 0, 1, 2, -1, -4])
// [[-1, 0, 1], [-1, -1, 2]]
threeSum([0, 1, 1])
// []
threeSum([0, 0, 0])
// [[0, 0, 0]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment