← Two PointersDSA 1.1.B

Opposite Ends + Sort

Sort first, then two-pointer from the ends — the k-Sum family. 3Sum, 4Sum, 3Sum Closest, Boats to Save People.

StatusCollected
Notes4 solved

Same opposite-ends shape as A, but with a sort step first — this is the whole k-Sum family: 3Sum, 4Sum, 3Sum Closest, Boats to Save People.

void threeSum(int *nums, int n) {
      sort(nums, n);
      for (int i = 0; i < n - 2; i++) {
          if (i > 0 && nums[i] == nums[i-1]) continue;   /* skip duplicate first elements */
          int l = i + 1, r = n - 1;
          while (l < r) {
              int sum = nums[i] + nums[l] + nums[r];
              if (sum == 0) {
                  /* record nums[i], nums[l], nums[r] */
                  while (l < r && nums[l] == nums[l+1]) l++;   /* skip duplicate left values */
                  while (l < r && nums[r] == nums[r-1]) r--;   /* skip duplicate right values */
                  l++; r--;
              } else if (sum < 0) l++;
              else r--;
          }
      }
  }

Fixing one element and running the opposite-ends scan on the rest is what turns 3Sum into Two Sum with an extra outer loop — and 4Sum is just that same idea nested one level deeper. The part that actually took a couple of attempts to get clean was managing the outer loop correctly at each level and skipping duplicates consistently, rather than the two-pointer core itself.

Notes from readers

Comments — via GitHub