Problem 707

Abstract / Summary

Design a data structure to store values in a sequence where you can add at the front, retrieve the first value, and check if it is empty.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0707.py

class Node:
    def __init__(self, val, next = None, prev = None):
        self.val  = val
        self.next = next

class MyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.size = 0

    def get(self, index: int) -> int:
        if index >= self.size:
            return -1

        scan = self.head
        for i in range(index):
            scan = scan.next
        return scan.val

    def addAtHead(self, val: int) -> None:
        node = Node(val)
        node.next = self.head
        self.head = node
        self.size += 1
        if self.size == 1:
            self.tail = self.head

    def addAtTail(self, val: int) -> None:
        if self.size == 0:
            self.addAtHead(val)
            return

        node = Node(val)
        self.tail.next = node
        self.tail      = node
        self.size     += 1

    def addAtIndex(self, index: int, val: int) -> None:
        if index > self.size:
            return # out of range: do nothing

        # specialized case for prepending and appending
        if index == 0:
            self.addAtHead(val)
            return
        if index == self.size:
            self.addAtTail(val)
            return

        # find predecessor
        scan = self.head
        for i in range(index - 1):
            scan = scan.next

        # insert node after
        node = Node(val)
        scan.next, node.next = node, scan.next
        self.size += 1

    def deleteAtIndex(self, index: int) -> None:
        if index >= self.size:
            return
        self.size -= 1

        # delete head
        if index == 0:
            self.head = self.head.next
            return

        # locate predecessor node
        scan = self.head
        for i in range(index - 1):
            scan = scan.next

        # delete tail
        if scan.next == self.tail:
            scan.next = None
            self.tail = scan
        else:
            scan.next = scan.next.next
81 lines | 2066 bytes | submitted October 18, 2023 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 31% (1+ million submissions).

Typical patterns to solve this problem:
  • Design
  • Linked List
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation provides a singly-linked list with a minimal public interface: element retrieval, insertion at the head, tail, or arbitrary index, and deletion by index. The class maintains explicit references to both the head and tail nodes together with a size counter, enabling constant-time checks for empty or single-element states. All operations are expressed in terms of straightforward pointer manipulation without auxiliary data structures.

Core Data Structures

The Node class stores a value and a reference to the next node. Although a prev parameter is accepted, it is never used, reinforcing the list’s singly-linked nature.

class Node:
    def __init__(self, val, next = None, prev = None):
        self.val  = val
        self.next = next

MyLinkedList holds three attributes: head, tail, and size. The head points to the first node, tail to the last node, and size tracks the number of elements, allowing O(1) boundary checks.

class MyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.size = 0

Retrieval (get)

The get method first validates the index against the current size. If the index is out of range, it returns -1. For a valid index, it walks from the head node forward index steps and returns the located node’s value.

def get(self, index: int) -> int:
    if index >= self.size:
        return -1

    scan = self.head
    for i in range(index):
        scan = scan.next
    return scan.val

Edge handling

  • Index equal to or larger than size triggers the early return.
  • The loop safely assumes scan is non-null because the size check guarantees the existence of the requested node.

Insertion at Head (addAtHead)

A new node is created, its next pointer is set to the current head, and then the list’s head reference is updated. The size counter is incremented. When the list transitions from empty to a single element, the tail reference is also aligned with the new head.

def addAtHead(self, val: int) -> None:
    node = Node(val)
    node.next = self.head
    self.head = node
    self.size += 1
    if self.size == 1:
        self.tail = self.head

Edge handling

  • The conditional if self.size == 1 captures the empty-list case, ensuring tail points to the sole node.

Insertion at Tail (addAtTail)

If the list is empty, the method delegates to addAtHead, guaranteeing correct initialization of both head and tail. Otherwise, a new node is appended after the current tail, the tail reference is moved forward, and the size counter is increased.

def addAtTail(self, val: int) -> None:
    if self.size == 0:
        self.addAtHead(val)
        return

    node = Node(val)
    self.tail.next = node
    self.tail      = node
    self.size     += 1

Edge handling

  • The early return for an empty list reuses the head-insertion logic, avoiding duplication.
  • Updating self.tail.next before moving self.tail preserves the chain.

Insertion at Arbitrary Index (addAtIndex)

The method first checks whether the index exceeds the current size; if so, it silently aborts. Special cases for inserting at the head (index == 0) and at the tail (index == self.size) are delegated to the respective methods, preserving their optimized paths.

For interior positions, the method walks to the node preceding the insertion point, creates a new node, and splices it into the list by adjusting two pointers in a single assignment statement.

def addAtIndex(self, index: int, val: int) -> None:
    if index > self.size:
        return  # out of range: do nothing

    # specialized case for prepending and appending
    if index == 0:
        self.addAtHead(val)
        return
    if index == self.size:
        self.addAtTail(val)
        return

    # find predecessor
    scan = self.head
    for i in range(index - 1):
        scan = scan.next

    # insert node after
    node = Node(val)
    scan.next, node.next = node, scan.next
    self.size += 1

Edge handling

  • The index > self.size guard prevents insertion beyond the list’s end.
  • Delegating to addAtHead and addAtTail ensures correct handling of empty or single-element lists.
  • The predecessor search loop runs index-1 times, guaranteeing that scan is never None when the insertion point is valid.

Deletion by Index (deleteAtIndex)

The method validates the index against the size, then decrements the size counter. Deleting the head updates the head reference directly. For other positions, it locates the predecessor node. If the node to be removed is the tail, the predecessor becomes the new tail and its next pointer is cleared. Otherwise, the predecessor’s next pointer is redirected to skip over the removed node.

def deleteAtIndex(self, index: int) -> None:
    if index >= self.size:
        return
    self.size -= 1

    # delete head
    if index == 0:
        self.head = self.head.next
        return

    # locate predecessor node
    scan = self.head
    for i in range(index - 1):
        scan = scan.next

    # delete tail
    if scan.next == self.tail:
        scan.next = None
        self.tail = scan
    else:
        scan.next = scan.next.next

Edge handling

  • The initial bounds check prevents underflow of the size counter.
  • Updating head for index 0 correctly handles removal of the first element, even when the list becomes empty (the tail remains unchanged until a subsequent operation corrects it).
  • The tail-removal branch ensures tail always points to the last node after deletion.

Edge Cases Managed Throughout

The code consistently guards against out-of-range indices in both retrieval and mutation methods. Empty-list scenarios are covered by early returns or by delegating to head-insertion logic. Single-element transitions are captured by size-based conditionals that synchronize head and tail. Deleting the last element updates the tail reference, preserving list integrity.

Performance Optimizations Observed

  • Maintaining a size field eliminates the need to traverse the list for length checks, enabling O(1) validation for all public methods.
  • Direct references to both head and tail allow constant-time insertion at either end without traversal.
  • The insertion at an interior index performs pointer updates in a single tuple assignment, reducing the number of statements executed.
  • Reusing addAtHead and addAtTail for boundary insertions avoids code duplication and leverages their optimized paths.
  • The deletion routine updates the size before any pointer manipulation, ensuring that size-dependent checks remain accurate even if an exception were to occur (though the code does not raise exceptions).
written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train made of individual toy cars hooked together. Each car holds a special number inside it. The first card representing the train keeps track of where the front car is, where the very last car is, and how many cars are attached in total.

When someone wants to look at a car at a certain spot, the train starts at the front and hops from one car to the next until it reaches the right place. To add a new car at the very front, a new car is made and hooked to the old first car, and then the train remembers that this new one is the new front. To add a car at the very back, the train finds the last car and hooks the new one right behind it.

If someone wants to put a car in the middle, the train walks along until it finds the car just before the spot where the new one belongs. It then carefully unhooks the next car, hooks the new one into that space, and connects the old one back on. Removing a car works just like a game of leapfrog. The train goes to the car right before the one being removed, skips over the unwanted car to hold hands with the one that comes after it, and the unwanted car simply disappears. This way, the line stays perfectly connected from start to finish no matter how many cars are added or taken away.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.07 | σ = 1.44

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go Rust TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
Dijkstra-Edu Java
everthis JS
fartem Ruby
halfrost Go
JoshCrozier JS
lkwq007 Python
lzl124631x C++
MacJim C++
muhammadfarhankt Go
ruoru Rust
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
lzl124631x C++
MacJim C++
muhammadfarhankt Go
ruoru Rust
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
34 links | 20 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 medium 1 hard
4 solutions   October 18, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality