Three Sum Problem

Published by persolut in

Write a function that returns all sets of three elements that sum to 0.

Examples

ThreeSum(new int[] { 0, 1, -1, -1, 2 }) ➞ { { 0, 1, -1 }, { -1, -1, 2 } }

ThreeSum(new int[] { 0, 0, 0, 5, -5 }) ➞ { { 0, 0, 0 }, { 0, 5, -5 } }

ThreeSum(new int[] { 1, 2, 3 }) ➞ { }

ThreeSum(new int[1]) ➞ { }

Notes

  • The original array may contain duplicate numbers.
  • Each three-element subarray in your output should be distinct.
  • Subarrays should be ordered by the first element of the subarray.
  • Subarrays themselves should be ordered the same as the original array.
  • Return an empty array if no three elements sum to zero.
  • Return an empty array if there are fewer than three elements.
Watch a quick demo on how Edabit works.