Skip to content

Latest commit

 

History

History
35 lines (31 loc) · 864 Bytes

15-3sum.md

File metadata and controls

35 lines (31 loc) · 864 Bytes

A video explaining this: https://youtu.be/QtbjaHkUzNo

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
  if (nums.length < 3) return []
  
  const result = []
  const hashes = new Set()
  
  // fix the left, the rest is the 2 sum problem
  for (let i = 0; i + 2 < nums.length; i++) {
    if (nums[i] === nums[i - 1]) continue
    const set = new Set()
    for (let j = i + 1; j < nums.length; j++) {
      const counterpart = -nums[i] - nums[j]
      if (set.has(counterpart)) {
        const min = Math.min(nums[i], nums[j], counterpart)
        const max = Math.max(nums[i], nums[j], counterpart)
        const hash = `${min}_${max}`
        if (!hashes.has(hash)) {
          result.push([min, -min-max,max])
          hashes.add(hash)
        }
      }
      set.add(nums[j])
    }
  }
  
  return result
};