Simplifying Linked-List interview tasks
Tags: linkedlist, leetcode, interview, javascript
Published: 2020-09-28 16:00:33

While I was **solving** one of [leetcode task](https://leetcode.com/problems/remove-linked-list-elements) 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](https://github.com/gkucmierz/algorithms/blob/master/js/linked_list.js)

Now with this abstraction solving [remove-linked-list-elements](https://leetcode.com/problems/remove-linked-list-elements) task is very easy, even monkey can do that!

### Complete solution

```javascript
// [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

```javascript
/*
 * 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.

```javascript
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.

```javascript
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*](https://leetcode.com/problems/remove-duplicates-from-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.

```javascript
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.app](https://instacode.app/run/FAYw9gdgzgLgBAGQJYQNYFMAmzZwLxwAUhAlPgHxwDewccAZgK4QgxKSJKwByY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