DSA GRIND #2

DSA GRIND #2


by Ashur Baroutta

    This week I spent most of my free time trying to come up with a solution for a problem called 3Sum. The problem statement reads "Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] equals 0". 

    A far from easy task for me to accomplish. Given the problem statement pointed out we cant have duplicates return in the trips, the first thing I did was sort the array so it'd be easier to iterate through and account for duplicates. I then initialized a new Linked List data structure in order to store the triplets as an array in each node. At this point I started a for loop and set the exit condition to be the length of the array-2, this is because I'm going to be using the last index as a right hand pointer that we keep sliding over (last index in arrays is always length-1).

    After this I set up various conditions to check for edge cases and situations in which the three separate indexes equaled 0. Whenever I found a triplet that did equal 0 I added the triplet to the linked list then I looped and incremented my left/decremented my right pointer by 1 until they moved passed any duplicates and repeated the same process. It is important to note that when they didnt equal 0, I would check if they were less then 0, as if they were then left pointer would be incremented by 1 since decrementing the right pointer would only ever make the end result smaller (remember we sorted the array already so reducing the value when theyre already less than 0 is counter productive.)

The results are below, might not be the fastest solution given its O(N^2) time complexity and O(N) space complexity. I am still pleased regardless and am going to be trying different problems similar to this in the following weeks. 


Comments

  1. Very nice work again, Ashur. Tackling problems like these will undoubtedly help with understanding vs. memorization-- and will help you be more versatile. Looking forward to the next one!

    ReplyDelete

Post a Comment

Popular posts from this blog

IP #6 : Reversing an Integer

IP#5 : LinkedList Removing Duplicates II