Grokking LinkedIn Coding Interview
Ask Author
Back to course home

0% completed

Vote For New Content
Easier to understand

Satappa khot

Jun 15, 2023

/** Sort the array , iterate over the array by having left and right pointers and find the sum. */ public Set<List<Integer>> searchTriplets2(int[] array) { Arrays.sort(array); Set<List<Integer>> triplets = new HashSet<>(); // Iterate only length -2 since you cant make triplets with only 2 elements for (int i = 0; i < array.length - 2; i++) { // Left is 1 ahead of i when it starts int right = array.length - 1; // Right always starts from the end int left = i+1; while (left < right) { int currentSum = array[i] + array[left] + array[right]; if (currentSum == 0) { triplets.add(Arrays.asList(array[i], array[left], array[right])); left++; right--; } else if (currentSum < 0) { left++; } else { right--; } } } return triplets; }

2

1

Comments
Comments
Adebowale Oduyemi
Adebowale Oduyemi2 years ago

While this is easy to understand, it is missing a final step. Good answer though!

public List<List<Integer>> searchTriplets(int[] array) { Arrays.sort(array); Set<List<Integer>> triplets = new HashSet<>(); // Iterate only length -2 since you ...

On this page