DEV Community

Aderibigbe Samuel
Aderibigbe Samuel

Posted on

Two Sum - LeetCode problem 1 solution in python

In this article, I will be sharing my approach to solving the Two sum problem on LeetCode. Like every other problem, the important thing is how you approach the problem or what we call an algorithm in programming, it does not really matter the language used. The approach in this tutorial can be used in any programming, not just python alone.

Motivation: I spend most of my free time on hackerRank and leetCode trying out different problems. This will help improve your problem-solving skills.

Two sum problems: Link to problem on leetCode

Image description
My First Approach The simple approach is to use two nested loops. when we have two nested loops, one is the outer loop while the other is the inner loop. Since the first input is a list, the outer loop iterates over all the elements of the list, and the inner loop iterates from the current index of the outer loop up to the end of the list. here's the part where you want to grab a pen and paper and write a simple algorithm

Image description

Writing the Code

Image description

✅ ✅ ✅ The code works

Image description

while the solution passed all the cases, You can see that the time complexity is not good enough and the code can be improved to execute faster. here the complexity is quadratic O(N²) which means the performance is proportional to the square of the size of the input elements. The code can be written efficiently if we make use of a dictionary and iterate over the list just once

✏️✏️ The Algorithmn

Image description
The code

Image description
✅ ✅ ✅ The code works: this time the code didn't just work but it was more faster

Image description

The complexity of this algorithm is O(n) which is faster than the one we implemented previously

Conclusion In this short guide, I showed you two approaches I used to solve the Two sum problem on leetCode. The first solution was good but not efficient while the second solution was more efficient. I hope I was able to make you see the importance of writing out your algorithm first before solving the problem and finally this approach can be used in other languages too.

say hi to me on Twitter @Sammie_savvie

Top comments (0)