IP#3 : LinkedLists Intro
LinkedList Intro
by Ashur Baroutta
Following up on our interview prep, while we are still working on numerous array problems, it's time to explore the LinkedList data structure problems and start building a strong foundation for those types of use cases. A LinkedList data structure is a list consisting of nodes where each node contains both a data field and a reference(link) to the next node in the list.
In the same spirit of our other submission, we will start with a problem statement that says "Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.". The visual representation of the linkedlist and desired output is as follows.
So the logic behind removing the duplicates in a linkedlist is a bit different than with an array. Given each node has a data field and a reference, we need to first initialize another node and set it equal to the ListNode being passed in (head). Then the idea is to keep looping until the next link in the list is null as that signifies the end of the list. So as we keep looping we need to work out way through the list and we want to check for when a given iteration's node value is equal to its reference(link) value. That way we can rearrange the links to remove any duplicate node.
After spending a few hours relearning how to make/access nodes, I was able to solve the problem and the code submission is as follows.
So as we can see, after we check to see if the data fields for the current node are equal to the next node's data, we set the current node's reference to the next node's reference field. Doing this we delete the middle link/duplicate by removing all of its connections!
While we successfully managed to complete the problem, there are issues with the solution. It has a very fast run time, though it is heavy on memory usage beating out only 37% of submissions in terms of memory utilization while being ranked 99% for speed, given we coded in Java there is a better way to manage memory while also completing our objective. I will continue working on the problem to better optimize memory efficiency.
Your persistence will continue to pay off, keep it up!!
ReplyDelete