Skip to content
Laviyx Learn

Try

DSA Linked Lists, Stacks, Trees and Heaps Practice

Practise building and manipulating linked lists, stacks, binary trees, binary search trees and heaps.

Intermediate8 problemsUpdated

Review first: Linked List Problems, Stacks, Tree Traversals, Binary Search Trees, Heaps and Priority Queues

  1. 1.Reverse a linked list

    Beginner

    Build the list 1 → 2 → 3 → 4 from Node objects, reverse it in place, and print the values of the reversed list.

    Show hint

    Walk the list with prev and current, saving current.next before pointing it back at prev.

    Show solution
    Python
    class Node:
        def __init__(self, value, next=None):
            self.value, self.next = value, next
    
    def reverse(head):
        prev = None
        while head:
            nxt = head.next
            head.next = prev
            prev, head = head, nxt
        return prev
    
    head = Node(1, Node(2, Node(3, Node(4))))
    node = reverse(head)
    values = []
    while node:
        values.append(node.value)
        node = node.next
    print(values)
    Output
    [4, 3, 2, 1]
  2. 2.Merge two sorted linked lists

    Intermediate

    Merge the sorted linked lists 1 → 3 → 5 and 2 → 4 → 6 → 8 into one sorted list by re-linking the nodes, and print its values.

    Show hint

    Use a dummy node in front of the result and a tail pointer; always attach the smaller front node.

    Show solution
    Python
    class Node:
        def __init__(self, value, next=None):
            self.value, self.next = value, next
    
    def merge(a, b):
        dummy = tail = Node(None)
        while a and b:
            if a.value <= b.value:
                tail.next, a = a, a.next
            else:
                tail.next, b = b, b.next
            tail = tail.next
        tail.next = a or b
        return dummy.next
    
    node = merge(Node(1, Node(3, Node(5))), Node(2, Node(4, Node(6, Node(8)))))
    values = []
    while node:
        values.append(node.value)
        node = node.next
    print(values)
    Output
    [1, 2, 3, 4, 5, 6, 8]
  3. 3.Days until warmer

    Intermediate

    For each day, print how many days you must wait for a warmer temperature (0 if never). Test [30, 38, 30, 36, 35, 40, 28].

    Show hint

    A monotonic stack of indexes whose temperatures are decreasing. When a warmer day arrives, pop and record the distance.

    Show solution
    Python
    def days_until_warmer(temps):
        result = [0] * len(temps)
        stack = []
        for i, t in enumerate(temps):
            while stack and temps[stack[-1]] < t:
                j = stack.pop()
                result[j] = i - j
            stack.append(i)
        return result
    
    print(days_until_warmer([30, 38, 30, 36, 35, 40, 28]))
    Output
    [1, 4, 1, 2, 1, 0, 0]
  4. 4.Maximum depth of a binary tree

    Beginner

    Write max_depth(node) that returns the number of nodes on the longest root-to-leaf path. Test it on a tree with root 3, children 9 and 20, where 20 has children 15 and 7.

    Show hint

    An empty tree has depth 0; otherwise 1 plus the larger depth of the two subtrees.

    Show solution
    Python
    class Node:
        def __init__(self, value, left=None, right=None):
            self.value, self.left, self.right = value, left, right
    
    def max_depth(node):
        if node is None:
            return 0
        return 1 + max(max_depth(node.left), max_depth(node.right))
    
    root = Node(3, Node(9), Node(20, Node(15), Node(7)))
    print(max_depth(root), max_depth(None))
    Output
    3 0

    This counts nodes, not edges, which is how most interview questions define depth. The tree lessons count edges, giving one less.

  5. 5.Are two trees identical?

    Beginner

    Write same_tree(a, b) that returns True when two binary trees have the same shape and values.

    Show hint

    Two empty trees are equal; if only one is empty, or the values differ, they are not; otherwise compare both pairs of subtrees.

    Show solution
    Python
    class Node:
        def __init__(self, value, left=None, right=None):
            self.value, self.left, self.right = value, left, right
    
    def same_tree(a, b):
        if a is None or b is None:
            return a is b
        return a.value == b.value and same_tree(a.left, b.left) and same_tree(a.right, b.right)
    
    print(same_tree(Node(1, Node(2), Node(3)), Node(1, Node(2), Node(3))))
    print(same_tree(Node(1, Node(2)), Node(1, None, Node(2))))
    Output
    True
    False
  6. 6.Sum of BST values in a range

    Intermediate

    Insert [10, 5, 15, 3, 7, 18] into a binary search tree, then write range_sum(node, low, high) that adds all values between low and high inclusive, skipping subtrees that cannot contain any. Print the sum for the range 7 to 15.

    Show hint

    If the node's value is below low, only the right subtree can help; if above high, only the left one.

    Show solution
    Python
    class Node:
        def __init__(self, value):
            self.value, self.left, self.right = value, None, None
    
    def insert(root, value):
        if root is None:
            return Node(value)
        if value < root.value:
            root.left = insert(root.left, value)
        else:
            root.right = insert(root.right, value)
        return root
    
    def range_sum(node, low, high):
        if node is None:
            return 0
        if node.value < low:
            return range_sum(node.right, low, high)
        if node.value > high:
            return range_sum(node.left, low, high)
        return node.value + range_sum(node.left, low, high) + range_sum(node.right, low, high)
    
    root = None
    for v in [10, 5, 15, 3, 7, 18]:
        root = insert(root, v)
    print(range_sum(root, 7, 15))
    Output
    32

    7 + 10 + 15 = 32. The BST property lets the search skip whole subtrees.

  7. 7.K closest points to the origin

    Intermediate

    Return the k points closest to (0, 0), closest first. Test the points [(1, 3), (-2, 2), (5, 8), (0, 1)] with k = 2.

    Show hint

    Compare squared distances x*x + y*y (no square root needed) and use heapq.nsmallest.

    Show solution
    Python
    import heapq
    
    def k_closest(points, k):
        return heapq.nsmallest(k, points, key=lambda p: p[0] * p[0] + p[1] * p[1])
    
    print(k_closest([(1, 3), (-2, 2), (5, 8), (0, 1)], 2))
    Output
    [(0, 1), (-2, 2)]

    The squared distances are 10, 8, 89 and 1. nsmallest uses a heap, O(n log k).

  8. 8.Last stone weight

    Intermediate

    Repeatedly smash the two heaviest stones together. Equal stones are both destroyed; otherwise the smaller is destroyed and the larger loses the smaller one's weight. Print the weight of the last stone, or 0. Test [2, 7, 4, 1, 8, 1].

    Show hint

    Use heapq as a max-heap by storing negated weights.

    Show solution
    Python
    import heapq
    
    def last_stone(stones):
        heap = [-s for s in stones]
        heapq.heapify(heap)
        while len(heap) > 1:
            a = -heapq.heappop(heap)
            b = -heapq.heappop(heap)
            if a != b:
                heapq.heappush(heap, -(a - b))
        return -heap[0] if heap else 0
    
    print(last_stone([2, 7, 4, 1, 8, 1]))
    print(last_stone([3, 3]))
    Output
    1
    0