<AI/>
enru
All posts

Design linked list

LeetCode 707: Design your own singly linked list with get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.

Difficulty
Medium
Published
Topics
#linked list#data structures
Open on LeetCode

Problem Description

Design your own implementation of a linked list. You can use a singly or doubly linked list.

A node in a singly linked list should have two attributes: val and next.

  • val: the value of the current node
  • next: a pointer/reference to the next node

If you want to use a doubly linked list, you'll need one more attribute, prev, pointing to the previous node in the list.

Note that nodes in the linked list are 0-indexed.

Implement the MyLinkedList class:

  • MyLinkedList() initializes the MyLinkedList object.
  • get(index: number): number returns the value of the node at index index. If the index is invalid, return -1.
  • addAtHead(val: number): void adds a node with value val to the beginning of the list.
  • addAtTail(val: number): void adds a node with value val to the end of the list.
  • addAtIndex(index: number, val: number): void adds a node with value val before the node at index index. If index equals the length of the list, the node is appended to the end. If index is greater than the length, the node is not inserted.
  • deleteAtIndex(index: number): void deletes the node at index index from the list.

Constraints

  • Each value in the list is in the range from 0 to 1000
  • The list contains from 0 to 1000 elements

Example

typescript
const myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1); // [1]
myLinkedList.addAtTail(3); // [1, 3]
myLinkedList.addAtIndex(1, 2); // [1, 2, 3]
myLinkedList.get(1); // 2
myLinkedList.deleteAtIndex(1); // [1, 3]
myLinkedList.get(1); // 3

The list ends up as [1, 3].

Singly linked list

Let's start with a simple MyLinkedList class with a constructor and empty stub methods.

typescript
type MyLinkedListNode = {
  val: number;
  next: MyLinkedListNode | null;
};
 
export class MyLinkedList {
  head: MyLinkedListNode | null;
  size: number;
 
  constructor() {
    this.head = null;
    this.size = 0;
  }
 
  get(index: number): number {
    return 0;
  }
 
  addAtIndex(index: number, val: number): void {}
 
  addAtHead(val: number): void {}
 
  addAtTail(val: number): void {}
 
  deleteAtIndex(index: number): void {}
}

Here we've defined the MyLinkedListNode type for a single node of the list and the class itself.

First, the class has a head field, which is null by default. This is the reference to the head of the list, i.e. its first element.

Second, you can't just get the size of a linked list, since counting the nodes requires walking the whole list from head to tail. To make our lives easier, we keep an internal size field in the class, which is initialized with zero and holds the size of the list. Every insertion increments it by 1, and every deletion decrements it by 1.

Getting an element

This method returns the value of the node at the given index.

First, we need to validate the index. If it's less than 0 or greater than or equal to size, we return -1, since such an index is invalid.

Next, we walk the list from its head to find the node with the given index. For that we run a loop while i < index. We initialize a variable curr with head, i.e. a reference to the first element of the list. On each iteration we set curr to the next element via curr.next.

If we find the node, we return its value; otherwise we return -1.

Adding an element at an index

First, we need to validate the index. If it's less than 0 or greater than size, we return without inserting anything.

Next, we increment the internal size field by one, since an element is being added.

If the index is 0, we're inserting at the beginning of the list. This means we just create a new node, point its next to the current head and replace head with the new node, then return.

If the index is not 0, we need to insert the node before the one currently at position index. For that we have a separate internal method findPrevNode. It returns the node prev that precedes the given index. If such a node exists, we set the new node's next to prev.next and then set prev.next to the new node. This way the new node is spliced into the chain at the required position.

Adding an element to the head

Since we already have a universal method for inserting at an index, we can reuse it to insert at the beginning. We just call it with index zero: this.addAtIndex(0, val)

Adding an element to the tail

Likewise, we can reuse the same method to insert at the end. We just call it with an index equal to the length of the list: this.addAtIndex(this.size, val)

Deleting an element

First, we need to validate the index. If it's less than 0 or greater than or equal to the size of the list, we return, since such an index is invalid.

Next, we decrement size by one, since an element is being removed.

If the index is zero, we're deleting the first element. In this case we just replace head with head.next.

Otherwise, we first find the node right before the one being deleted. Then we link the previous node to the next one: prev.next = prev.next.next.

Implementation

typescript
type MyLinkedListNode = {
  val: number;
  next: MyLinkedListNode | null;
};
 
export class MyLinkedList {
  head: MyLinkedListNode | null;
  size: number;
 
  constructor() {
    this.head = null;
    this.size = 0;
  }
 
  private findPrevNode(index: number): MyLinkedListNode | null {
    let curr = this.head;
    for (let i = 0; i < index - 1; i++) {
      if (curr) {
        curr = curr.next;
      }
    }
 
    return curr;
  }
 
  get(index: number): number {
    if (index >= this.size || index < 0) {
      return -1;
    }
 
    let curr = this.head;
    for (let i = 0; i < index; i++) {
      if (curr) {
        curr = curr.next;
      }
    }
 
    return curr ? curr.val : -1;
  }
 
  addAtHead(val: number): void {
    this.addAtIndex(0, val);
  }
 
  addAtTail(val: number): void {
    this.addAtIndex(this.size, val);
  }
 
  addAtIndex(index: number, val: number): void {
    if (index > this.size || index < 0) {
      return;
    }
 
    this.size++;
 
    if (index === 0) {
      this.head = { val, next: this.head };
      return;
    }
 
    const prev = this.findPrevNode(index);
 
    if (prev) {
      prev.next = { val, next: prev.next };
    }
  }
 
  deleteAtIndex(index: number): void {
    if (index < 0 || index >= this.size) {
      return;
    }
 
    this.size--;
 
    if (index === 0 && this.head) {
      this.head = this.head.next;
      return;
    }
 
    const prev = this.findPrevNode(index);
 
    if (prev && prev.next) {
      prev.next = prev.next.next;
    }
  }
}

Complexity Analysis

Time Complexity

Since we're designing a data structure, we need to analyze each of its methods.

  • get is O(n), since finding the node may require walking the whole list.
  • addAtIndex is O(n), since finding the node before which to insert may require walking the whole list.
  • addAtTail is O(n), just like addAtIndex.
  • addAtHead is O(1), since there's no need to walk the list.
  • deleteAtIndex is O(n), since finding the node may require walking the whole list. Only deleting the first element runs in constant time O(1).

Space Complexity

O(1) for all operations.