-
-
Notifications
You must be signed in to change notification settings - Fork 449
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added solution for Leetcode Problem #15 (3Sum) in Dart
- Implemented the hreeSum function to find all unique triplets that sum up to zero. - Included a time complexity of O(N^2) and space complexity of O(1). - Added unit tests with edge cases for validation.
- Loading branch information
1 parent
4998823
commit f0ee9fb
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
//Leetcode problem no. 15: https://leetcode.com/problems/3sum/description/ | ||
//Time Complexity: O(N^2) | ||
//Space Complexity: O(1) | ||
|
||
//Input: A list of integers | ||
//Output: A list of lists containing all those integers whose sum end up to 0 | ||
|
||
import 'package:test/test.dart'; | ||
|
||
import '../sort/heap_Sort.dart'; | ||
|
||
List<List<int>> threeSum(List<int> l){ | ||
List<List<int>> ans=[]; | ||
sort(l); | ||
for(int i=0; i<l.length; ++i){ | ||
if(i!=0 && l[i]==l[i-1]) continue; | ||
int j=i+1, k=l.length-1; | ||
while(j<k){ | ||
int sum=l[i]+l[j]+l[k]; | ||
if(sum<0) j++; | ||
else if(sum>0) k--; | ||
else{ | ||
ans.add([l[i], l[j], l[k]]); | ||
j++; | ||
k--; | ||
while(j<k && l[j]==l[j-1]) j++; | ||
while(j<k && l[k]==l[k+1]) k--; | ||
} | ||
} | ||
} | ||
return ans; | ||
} | ||
|
||
void main(){ | ||
test('test 1', () { | ||
expect(threeSum([-1,0,1,2,-1,-4]), [[-1,-1,2],[-1,0,1]]); | ||
}); | ||
|
||
test('test 2', () { | ||
expect(threeSum([0, 1, 1]), []); | ||
}); | ||
|
||
test('test 3', () { | ||
expect(threeSum([0, 0, 0]), [[0,0,0]]); | ||
}); | ||
} |