Skip to main content

Posts

Balanced Trees

Balanced Trees Balanced Trees Balanced search trees are among the most useful and versatile data structures. Many programming languages include balanced search trees in their standard libraries. e.g. C++: std::map , Java: TreeMap , Python: dict , etc. Many advanced data structures are layered on top of balanced search trees.. A quick BST recap A binary search tree is a binary tree where each node has a key and a value, and the following properties hold: Each node in the BST stores a key, and optinally, some information associated with the key. The keys in the left subtree are less than the key in its parent node, and the keys in the right subtree are greater than the key in its parent node. The height of a BST is the number of nodes on the longest path from the root to a leaf. A tree with one node has height 0, A tree with no nodes has height -1. Deleting from a BST Deleting a n...

Range Minimum Query

Range Minimum Queries Range Minimum Queries Problem Statement Given an array of integers, find the minimum value in a given range. A trivial solution The trivial solution is to iterate over the range and find the minimum value. This takes O(n) time. A Different Approach There are only O(n^2) possible ranges in an array of size n. So, we can precompute the minimum value for all possible ranges in O(n^2) time. This takes O(n^2) space. We'll say that an RMQ data structure has time complexity < p ( n ) , q ( n ) > <p(n),q(n)> < p ( n ) , q ( n ) > if it can be precomputed in O ( p ( n ) ) O(p(n)) O ( p ( n )) time and answer queries in O ( q ( n ) ) O(q(n)) O ( q ( n )) time. We have two different approaches to RMQ: Precompute all possible ranges in O ( n 2 ) O(n^2) O ( n 2 ) time and answer queries in O ( 1 ) O(1) O ( 1 ) time. This is < O ( n 2 ) , O ( 1...