All files / leetCode 0015.ts

100% Statements 28/28
100% Branches 14/14
100% Functions 2/2
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45  6x   6x 2x   43x   4x   13x 3x   10x 10x   10x 32x   32x 12x 12x 12x 12x     12x 6x 12x 1x 20x 9x   11x         10x 4x     4x    
export default function threeSum(nums: number[]): number[][] {
  const solution: number[][] = []
 
  if (nums.length <= 2)
    return solution
 
  nums.sort((a, b) => a - b)
 
  for (let i = 0; i < nums.length - 2; i++) {
    // No answer when nums sorted
    if (nums[i] > 0)
      break
 
    let j = i + 1
    let k = nums.length - 1
 
    while (j < k) {
      const cur: number[] = []
 
      if (nums[i] + nums[j] + nums[k] === 0) {
        cur.push(nums[i], nums[j], nums[k])
        solution.push(cur)
        j++
        k--
 
        // Skip duplicated elements
        while (j < k && nums[j - 1] === nums[j])
          j++
        while (j < k && nums[k] === nums[k + 1])
          k--
      } else if (nums[i] + nums[j] + nums[k] < 0) {
        j++
      } else {
        k--
      }
    }
 
    // Skip duplicated elements
    while (i < nums.length - 2 && nums[i] === nums[i + 1])
      i++
  }
 
  return solution
}