Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Reverse Linked List

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "206" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is the range [0, 5000]. -5000 <= Node.val <= 5000 Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

Explanation

Okay, here's a breakdown of the solution, followed by the Python code.

  • Iterative Approach: The iterative approach involves traversing the list while changing the next pointer of each node to point to its previous node. We maintain three pointers: prev, curr, and next_node.
  • Recursive Approach: The recursive approach involves reversing the rest of the list after the head node and then making the head node the last node.

  • Time & Space Complexity: O(n) time complexity (both iterative and recursive), O(1) space complexity for iterative, and O(n) space complexity for recursive due to the call stack.

Code

    # Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        """
        Reverses a singly linked list iteratively.
        """
        prev = None
        curr = head

        while curr:
            next_node = curr.next
            curr.next = prev
            prev = curr
            curr = next_node

        return prev

    def reverseListRecursive(self, head: ListNode) -> ListNode:
        """
        Reverses a singly linked list recursively.
        """
        if not head or not head.next:
            return head

        new_head = self.reverseListRecursive(head.next)
        head.next.next = head
        head.next = None
        return new_head

More from this blog

C

Chatmagic blog

2894 posts