DEV Community

Cover image for Simplifying Linked-List interview tasks
Grzegorz Kućmierz
Grzegorz Kućmierz

Posted on • Updated on

Simplifying Linked-List interview tasks

While I was solving one of leetcode task I came upon idea that there is many similar tasks in many places. All of them are very similar, but they require much code writing and precise testing.

So to simplify solving further tasks I created JavaScript code, that implements popular methods on linked lists and accepts any type of node implementation.

I have put it on my github

Now with this abstraction solving remove-linked-list-elements task is very easy, even monkey can do that!

Complete solution

// [put LinkedList code here]

const removeElements = (head, val) => {
  const ll = LinkedList();
  return ll.removeItems(head, v => v === val);
};
Enter fullscreen mode Exit fullscreen mode

First

Create linkedList instance by passing function that is creating node list

/*
 * function ListNode(val = 0, next = null) {
 *   return { val, next };
 * }
 */

const linkedList = LinkedList((value, next) => {
  return new ListNode(value, next);
});
Enter fullscreen mode Exit fullscreen mode

In my case I don't need to pass this function because it is by default exactly matching to LeetCode Linked Node constructor.

Second

Just call removeItems method and return head of this list.

return linkedList.removeItems(head, v => v === val);
Enter fullscreen mode Exit fullscreen mode

Be aware, that in this LeetCode task you can't just convert existing list to array, filter it, and convert back to list. This task also checks references, so if you try to submit that kind of code it should not pass.

const removeElements = (head, val) => {
    const ll = LinkedList();
    return ll.array2list(
        ll.list2array().filter(v => v === val)
    );
};
Enter fullscreen mode Exit fullscreen mode

Now solving this type of tasks is super easy.

Delete duplicates task

Let's try to solve another task which is deleting duplicates in sorted list

This list is sorted, so any duplicates will be next to each other, so we can write simple code, that is comparing current value to last seen value and update it when it is changed.

const deleteDuplicates = head => {
    let lastVal;
    return LinkedList().removeItems(head, val => {
        if (val === lastVal) return true;
        lastVal = val;
        return false;
    });
};
Enter fullscreen mode Exit fullscreen mode

Very simple code. Writing this complete solution took less than 60 seconds.

Playground

Here you can play with this code a little bit:
instacode.app

Top comments (0)