Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Convert Sorted List to Binary Search Tree

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "109" 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 where elements are sorted in ascending order, convert it to a height-balanced binary search tree. Example 1: Input: head = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. Example 2: Input: head = [] Output: [] Constraints: The number of nodes in head is in the range [0, 2 * 104]. -105 <= Node.val <= 105

Explanation

Here's the approach to convert a sorted linked list to a height-balanced BST:

  • Find the Middle Node: The middle node of the linked list will be the root of our BST. Since the list is sorted, the middle element ensures balance.
  • Recursive Construction: Recursively build the left subtree from the portion of the linked list before the middle node, and the right subtree from the portion after the middle node.
  • Base Case: If the list is empty, return None.

  • Time Complexity: O(n), where n is the number of nodes in the linked list.

  • Space Complexity: O(log n) due to the recursion stack.

Code

    class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def sortedListToBST(head: ListNode) -> TreeNode:
    """Converts a sorted linked list to a height-balanced BST."""

    def find_middle(head: ListNode) -> ListNode:
        """Finds the middle node of the linked list."""
        slow, fast = head, head
        prev = None  # Keep track of the node before slow

        while fast and fast.next:
            prev = slow
            slow = slow.next
            fast = fast.next.next

        return slow, prev  # Return the middle node and its previous node.

    def build_bst(head: ListNode) -> TreeNode:
        """Recursively builds the BST."""
        if not head:
            return None

        middle, prev = find_middle(head)

        if prev:
            prev.next = None  # Split the list into two halves

        root = TreeNode(middle.val)

        if head == middle:  # Handle single node case after split
            return root

        if prev is None: # Handle single node list
            root.left = None
        else:
            root.left = build_bst(head) # Left side from head till the split

        root.right = build_bst(middle.next) # Right side from middle to end
        return root

    return build_bst(head)

More from this blog

C

Chatmagic blog

2894 posts