Replace every element with the least greater element on its right

Pattern: Floor and ceil

medium

Go from right to left, inserting each value into a BST of the values to its right. While inserting, every time the path turns left the current node is bigger than the new value; the last such node is the smallest bigger value.

The problem

Replace each element with the smallest element to its right that is greater than it, or -1 if there is none. [2, 6, 9, 1, 3, 2] gives [3, 9, -1, 2, -1, -1].

Think first

  • Which values can be the answer for arr[i]?
  • Which structure finds the smallest value above x among many?
  • Why go from the right?

Hints

    Brute force, and why it fails

    For each element, scan everything to its right: O(n²).

    The key insight

    Inserting into a BST walks past the candidates; the last left turn is at the least greater value.

    Dry run

    out_ _ _ _ -1 -1

    arr = [2, 6, 9, 1, 3, 2]. From the right: the last 2 becomes the root (-1). 3 goes right of 2 (-1).

    Step 1 of 3

    The plan

    for i from n - 1 down to 0: best = -1; insert arr[i], setting best = node at each left turn; out[i] = best
    

    Complexity

    Time
    O(n h)
    Space
    O(n)

    A balanced tree (TreeSet, std::set) would make it O(n log n).

    Edge cases

    • All equal: all -1.
    • Decreasing array: -1 for the last, and so on.
    • One element.
    I've built my logic, show the code

    Java

    class Solution {
        private static class Node {
            int val;
            Node left, right;
            Node(int v) { val = v; }
        }
    
        private int best;
    
        public int[] findLeastGreater(int[] arr) {
            int n = arr.length;
            int[] out = new int[n];
            Node root = null;
            for (int i = n - 1; i >= 0; i--) {      // from the right, so the BST holds everything to the right
                best = -1;
                root = insert(root, arr[i]);        // the last node we turn left at is the least greater value
                out[i] = best;
            }
            return out;
        }
    
        private Node insert(Node n, int v) {
            if (n == null) return new Node(v);
            if (v < n.val) { best = n.val; n.left = insert(n.left, v); }
            else n.right = insert(n.right, v);
            return n;
        }
    }

    C++

    class Solution {
    public:
        struct Node {
            int val;
            Node* left;
            Node* right;
            Node(int v) : val(v), left(NULL), right(NULL) {}
        };
    
        int best;
    
        vector<int> findLeastGreater(vector<int>& arr) {
            int n = static_cast<int>(arr.size());
            vector<int> out(n);
            Node* root = NULL;
            for (int i = n - 1; i >= 0; i--) {      // from the right, so the BST holds everything to the right
                best = -1;
                root = insert(root, arr[i]);        // the last node we turn left at is the least greater value
                out[i] = best;
            }
            return out;
        }
    
        Node* insert(Node* n, int v) {
            if (n == NULL) return new Node(v);
            if (v < n->val) { best = n->val; n->left = insert(n->left, v); }
            else n->right = insert(n->right, v);
            return n;
        }
    };

    Python

    class Solution:
        def findLeastGreater(self, arr: list[int]) -> list[int]:
            root, out = None, [0] * len(arr)        # nodes are [val, left, right]
            for i in range(len(arr) - 1, -1, -1):   # from the right, so the BST holds everything to the right
                v, best = arr[i], -1
                if root is None:
                    root = [v, None, None]
                else:
                    n = root
                    while True:
                        side = 1 if v < n[0] else 2
                        if side == 1:
                            best = n[0]             # the last node we turn left at is the least greater value
                        if n[side] is None:
                            n[side] = [v, None, None]
                            break
                        n = n[side]
                out[i] = best
            return out

    Common mistakes

    • Counting equal values as greater.
    • Going from left to right.

    Similar problems