Three Number Sum in Python

I recently created a solution for the three number sum problem in JavaScript, and now that I want to practice my Python, I thought I’d create a similar solution in Python. Let’s begin.

The Prompt

Create a function that takes an array and a target integer that represents the sum. The function should find all triplets in the array that sum up to the target integer.

The numbers should be in ascending order.

If on three numbers sum up to the target integer, then the function should return an empty array.

The Code

First, we’ll be sorting the array and create a variable to represent the final array.

Now, we’ll initiate a for loop to traverse the input array. At the same time, we’l create a left and right variable(s) that will act as pointers.

Now, while the left value is less than the right value, create a variable that will act as the current sum, this will be a comparison to the target sum

If the current sum is equal to the target sum, then we’ll need to append the value to the array we created.

If the value was less than the target, then we’ll have to increment the left value.

If the value was greater than the target, then decrement the right value.

Finally, return the array representing the triplets.

The final code should look like the following:

Complexity Analysis

The time complexity of this solution is O(n ^ 2) time, where (n) represents the length of the input array.

The space complexity of this solution is O(n) space, since we’re created an array to store our final values.

Thank you so much for reading this article.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store