If you’re preparing for technical interviews or want to improve your coding skills, solving practice problems on LeetCode is a great way.
In this post, we’ll discuss a solution to the “3 sum” problem on LeetCode.
One solution to this problem is to use a brute force approach, where we consider every possible combination of three elements and check if their sum is zero. However, this solution has a time complexity of O(n^3), which is not efficient for large inputs.
A better solution is to use a two-pointer approach. We can sort the array first, and then for each element a in the array, we can use two pointers b and c to find the other two elements that sum to -a. We can move the pointers b and c towards each other to find the other two elements.
Here is the solution :
This solution has a time complexity of O(n^2) and a space complexity of O(1), which is much more efficient than the brute force approach.
I hope this helps! Let me know if you have any questions or suggestions for improvement.