Linked List Interview Questions

Here’s a list of the most commonly asked linked list interview questions, along with explanations and sample code to help you ace your next technical interview.
Share on :

Introduction

Linked lists are a fundamental data structure in computer science, often used in interviews to assess candidates' understanding of memory management, data structure manipulation, and algorithmic thinking. Linked lists are dynamic, allowing efficient insertions and deletions, and are particularly useful for certain memory-constrained applications. Here’s a list of the most commonly asked linked list interview questions, along with explanations and sample code to help you ace your next technical interview.

1. What is a Linked List, and How is it Different from an Array?

A linked list is a linear data structure where each element, called a node, contains a value and a pointer (or reference) to the next node in the sequence. Linked lists are dynamic and can grow or shrink in size by simply modifying pointers.

Key Differences:

  • Dynamic Size: Linked lists can grow or shrink dynamically, while arrays have a fixed size.
  • Memory Allocation: Linked lists allocate memory on demand, while arrays allocate a fixed block of memory.
  • Access Time: Arrays allow constant-time access to elements, whereas linked lists require traversal from the head node, making access time linear.

2. How Do You Implement a Singly Linked List?

A singly linked list is a linked list in which each node points to the next node in the sequence but has no reference to the previous node.

Example of Singly Linked List Implementation:

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

class SinglyLinkedList:
    def __init__(self):
        self.head = None

    def append(self, value):
        new_node = Node(value)
        if not self.head:
            self.head = new_node
            return
        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node

In this example, append adds a node to the end of the list.

3. How Do You Reverse a Linked List?

Reversing a linked list involves changing the next pointer of each node to point to its previous node. This operation requires reassigning pointers iteratively or using recursion.

Example Code for Reversing a Linked List:

def reverse_linked_list(head):
    prev = None
    current = head
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    return prev  # New head of the reversed list

4. How Do You Detect a Cycle in a Linked List?

To detect a cycle in a linked list, you can use the Floyd’s Cycle Detection Algorithm (or "tortoise and hare" method), where two pointers move at different speeds. If they eventually meet, there is a cycle.

Example of Cycle Detection:

def has_cycle(head):
    slow = head
    fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True
    return False

5. How Do You Find the Middle Element of a Linked List?

To find the middle element, use two pointers: one moves one step at a time (slow), and the other moves two steps at a time (fast). When the fast pointer reaches the end, the slow pointer will be at the middle.

Example Code to Find the Middle Element:

def find_middle(head):
    slow = head
    fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow  # Middle node

6. How Do You Remove the N-th Node from the End of a Linked List?

To remove the N-th node from the end, use a two-pointer technique. Move the second pointer n steps ahead, then move both pointers together until the second pointer reaches the end.

Example Code for Removing N-th Node from End:

def remove_nth_from_end(head, n):
    dummy = Node(0)
    dummy.next = head
    first = dummy
    second = dummy
    for _ in range(n + 1):
        second = second.next
    while second:
        first = first.next
        second = second.next
    first.next = first.next.next
    return dummy.next

7. How Do You Merge Two Sorted Linked Lists?

To merge two sorted linked lists, compare the head nodes of both lists and repeatedly attach the smaller node to a new linked list.

Example Code to Merge Two Sorted Linked Lists:

def merge_two_lists(l1, l2):
    dummy = Node(0)
    tail = dummy
    while l1 and l2:
        if l1.value < l2.value:
            tail.next = l1
            l1 = l1.next
        else:
            tail.next = l2
            l2 = l2.next
        tail = tail.next
    tail.next = l1 if l1 else l2
    return dummy.next

8. How Do You Remove Duplicates from a Sorted Linked List?

To remove duplicates from a sorted linked list, iterate through the list and compare each node with the next node. If they are the same, skip the next node.

Example Code to Remove Duplicates:

def remove_duplicates(head):
    current = head
    while current and current.next:
        if current.value == current.next.value:
            current.next = current.next.next
        else:
            current = current.next
    return head

9. How Do You Check if Two Linked Lists Intersect?

To check if two linked lists intersect, traverse each list and store nodes in a set or use a two-pointer approach to detect an overlap.

Example Code to Check for Intersection:

def get_intersection_node(headA, headB):
    nodes_in_A = set()
    while headA:
        nodes_in_A.add(headA)
        headA = headA.next
    while headB:
        if headB in nodes_in_A:
            return headB
        headB = headB.next
    return None

10. How Do You Find the Length of a Linked List?

To find the length of a linked list, traverse the list while counting the number of nodes.

Example Code to Find the Length:

def find_length(head):
    length = 0
    current = head
    while current:
        length += 1
        current = current.next
    return length

Conclusion

Linked lists are versatile data structures, and mastering these questions will prepare you well for data structure-related interviews. By understanding common operations like reversing, detecting cycles, finding intersections, and removing duplicates, you'll be equipped to handle both basic and advanced linked list questions.

FAQs

What is the difference between a singly and a doubly linked list?

A singly linked list has nodes that point only to the next node, whereas a doubly linked list has nodes with pointers to both the next and the previous nodes, allowing for bi-directional traversal.

How can I delete a node in a linked list with only a pointer to that node?

If you only have access to the node to be deleted, copy the data from the next node into the current node and delete the next node to effectively "delete" the target node.

What is the time complexity of inserting a node in a linked list?

For both singly and doubly linked lists, the time complexity of inserting a node at the beginning is O(1). For insertion at the end, it is O(n) if you don't have a tail pointer.

How is a circular linked list different from a regular linked list?

In a circular linked list, the last node points back to the first node, forming a loop. This differs from a regular linked list where the last node points to null.

Can linked lists be used to implement other data structures?

Yes, linked lists can be used to implement stacks, queues, and other dynamic data structures due to their efficient insertion and deletion capabilities.