Home Posts Tags Post Search Tag Search

Post 44

Hacker Rank 18 - Valid BTS Tree

Published on: 2025-06-23 Tags: elixir, Side Project, Hacker Rank
Okay so for this one we need to figure out if a preordered list is a valid BTS tree.

Sample Input
5 # number of cases (only one of these) repeat the next 2 lines that many times
3 # number of nodes
1 2 3 # nodes 
3
2 1 3
6
3 2 1 5 4 6
4
1 3 4 2
5
3 4 5 1 2

Sample Output
YES
YES
YES
NO
NO


Okay so for this we need to find out if its valid. We will accomplish this by keep a stack of the current side we are on and then keeping a min that we can check against once we get though the left side and there is no issues.

    # Validates if the given list can be preorder traversal of a BST
    def valid_preorder?(preorder) do
      valid_preorder(preorder, [], - :math.pow(2, 64))
    end
  
    # Successfully reached the end of the sequence without violating BST rules.
    defp valid_preorder([], _stack, _min), do: true
  
    # Violation: current value is smaller than allowed based on BST constraints.
    defp valid_preorder([x | _rest], _stack, min) when x < min, do: false
  
    # Try inserting current value. Pop from stack while current > top to simulate right subtree.
    defp valid_preorder([x | rest], stack, min) do
      {stack, min} = pop_stack(x, stack, min)
      valid_preorder(rest, [x | stack], min)
    end
  
    # Stack is empty - nothing to pop.
    defp pop_stack(_x, [], min), do: {[], min}
  
    # Pop values smaller than current, updating min - simulating move up before going right.
    defp pop_stack(x, [top | rest], _min) when x > top do
      pop_stack(x, rest, top)
    end
  
    # Current value fits in subtree. Stop popping.
    defp pop_stack(_x, stack, min), do: {stack, min}

This is the logic of the code above:
Iterate through each number in the given preorder list, one by one.

Maintain a stack to simulate the path we're taking down the BST.

For each number:

    If it's less than the current min, it violates the BST preorder rule:

        This means we’ve gone into the right subtree of some node, and we’re now seeing a value that should have been on the left.

        So we return false.

If the current number is greater than the top of the stack, it means:

    We’ve finished the left subtree and are now moving back up the tree.

    While the current value is greater than the stack’s top, pop from the stack.

    Each popped value becomes the new min, because any future value must now be greater than that.

    This simulates moving up and starting a right subtree.

Push the current number onto the stack — we're moving deeper into the tree.

As per usual the print is up to the reader.