Skip to content

Bug Report for singlyLinkedList #5222

@hash-walker

Description

@hash-walker

Bug Report for https://neetcode.io/problems/singlyLinkedList

Please describe the bug below and include any steps to reproduce the bug or screenshots if possible.

def remove(self, index: int) -> bool:
    i = 0
    curr = self.head
    while i < index and curr:
        i += 1
        curr = curr.next
    
    # Remove the node ahead of curr
    if curr and curr.next:
        if curr.next == self.tail:
            self.tail = curr
        curr.next = curr.next.next
        return True
    return False

it include a bug where it removes the node after the index and not the exact index

we can have something like this:

def remove(self, index: int) -> bool:
    cur = self.head
    i = 0

    if self.head == None:
        return False

    if index == 0:
        if cur.next == None:
            self.head = None
            self.tail = None
        else:
            self.head = cur.next

        return True
    
    while cur.next:

        if i+1 >= index:
            if cur.next == self.tail:
                self.tail = cur
            cur.next = cur.next.next
            
            return True

        cur = cur.next
        i += 1

    return False

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions