IP#4 : LinkedList improvement
LinkedList improvement
Ashur Baroutta
In the previous submission, we worked on a LinkedList problem and got our solution to a point where the run time was very fast, though our memory management was ranked quite low in comparison. That didn't sit well, so today we try to tackle optimizing it in terms of memory efficiency. Our original solution for the problem, deleting duplicates, is as follows.
So while the solution is acceptable, it exposed a weakness in my line of thinking. Fewer lines of code, or fewer words, does not inherently mean fewer resources utilized while code is compiled and executed. It seemed natural to think but I need to break this idea.
After working through different types of solutions and researching a better way to solve the problem in terms of speed and memory usage. I was able to manage the following.
Originally, I just started with one node and iterated through the list with a basic while loop. This time, what I did is had a node pointing to head (head is the first node in a list) and a second node pointing to heads.next reference (in other words the node after head).
The logic itself is very similar though reading it you can see it digests a bit different. So with this solution we move the links of both nodes linearly through the list. However, once the value fields in both nodes are equal(b.val -- a.val), what we do is change the links for both nodes by first setting the b node to its next reference and only then setting a's next reference to the b node. Since we set be prior to resetting a's reference, when we reestablish the link between nodes, we've jumped over the node needing to be deleted thus removing it.
While not drastically different, our speed and memory was able to make a giant leap in terms of ranking. Our stats for this submissions rankings are as follows. I am very pleased with the improvement, and look forward to working more with this data structure as i continue my prep.
Great job with the pivot! Always such a rewarding feeling. Enjoy!
ReplyDelete