All files / leetCode 0018.ts

100% Statements 31/31
100% Branches 18/18
100% Functions 2/2
100% Lines 28/28

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 46 47 48 49  6x   6x 3x   44x   3x   14x 6x   8x   30x 15x   15x 15x   15x 42x   42x 12x 12x 12x 12x 12x     12x 8x   12x 2x 30x 15x   15x           3x    
export default function fourSum(nums: number[], target: number): number[][] {
  const solution: number[][] = []
 
  if (nums.length <= 3)
    return solution
 
  nums.sort((a, b) => a - b)
 
  for (let i = 0; i < nums.length - 3; i++) {
    // Skip duplicated elements
    if (i > 0 && nums[i - 1] === nums[i])
      continue
 
    for (let j = i + 1; j < nums.length - 2; j++) {
      // Skip duplicated elements
      if (j > i + 1 && nums[j - 1] === nums[j])
        continue
 
      let k = j + 1
      let l = nums.length - 1
 
      while (k < l) {
        const sum = nums[i] + nums[j] + nums[k] + nums[l]
 
        if (sum === target) {
          const cur = []
          cur.push(nums[i], nums[j], nums[k], nums[l])
          solution.push(cur)
          k++
          l--
 
          // Skip duplicated elements
          while (k < l && nums[k - 1] === nums[k])
            k++
 
          while (k < l && nums[l] === nums[l + 1])
            l--
        } else if (sum < target) {
          k++
        } else {
          l--
        }
      }
    }
  }
 
  return solution
}