DEV Community

loading...
Cover image for Simplifying Linked-List interview tasks

Simplifying Linked-List interview tasks

gkucmierz profile image Grzegorz Kućmierz ・2 min read

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);
};

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);
});

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);

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)
    );
};

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;
    });
};

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

Playground

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

Discussion (0)

Forem Open with the Forem app