life is too short for a diary

Three Sum Problem Leetcode Solution

Tags: leetcode two pointers java

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.1

Brute force algorithm

This solution will result in Time Limit Exceeded since it has complexity of O(n3). We can naively check for all combination of array in three nested loops.

More efficient solution

Using two pointer solution, we can acheive O(n2) time complexity.


  1. Leetcode

comments powered by Disqus