DEV Community

erhallow
erhallow

Posted on

Three-Number Sum or Triplet Sum

Python

Step 1: Thought Process / Set up

  • Is the array sorted? If not, I will sort the array.
  • With sorted arrays, I like to utilize pointers
  • Loop through the array with a for loop
  • Move pointers using if statements inside the loop

    Step: 2: Function Set Up

    def triplet(array, sum);
      array.sort()
      three_sum = []
      for :
        if
        elif
      return three_sum
    

    Here is the basic outline of the problem we will solve. We define a function with parameters of an array and sum. I use the basic sorting method to sort the array. I set up an empty list that we will add our three number sum to.

    Now that I have the skeleton of the problem, we can start filling out the rest.

    for i in range(len(array)-2):
    
    

    Because we are looking for a three number sum, we will loop through the array and stop before the last two elements.

  • Top comments (0)