Problem
You are tasked with implementing a segment tree using Java and Python to calculate the maximum value in a given range [left, right] of an array. A segment tree allows both querying and updating efficiently.
The main operations are:
- Build: Construct the segment tree from a given array.
- Update: Modify a specific index in the array and update the segment tree accordingly.
- Query: Find the maximum value in a given range
[left, right].
Examples
Example 1
| |
Example 2
| |
Solution
Method 1 - Using the segment tree
A segment tree is an efficient way to perform range queries such as maximum, minimum, or summation operations. The tree is built such that:
- Each leaf node contains an element of the array.
- Internal nodes represent aggregate information over their child nodes (in this case, the maximum value).
Key insight:
- A query for the maximum in a range
[left, right]moves through specialised paths divided into segments within the tree hierarchy.
Approach
- Tree Representation:
- Use a size of
2 * nto store both leaves and internal nodes. - The leaves of the segment tree contain the original array values.
- Use a size of
- Build:
- Populate the leaves with array values.
- Compute the maximum values for internal nodes, moving from the bottom up.
- Update:
- Update values at the leaf node corresponding to the array index.
- Propagate the changes upwards, recalculating maximums along the way.
- Query:
- Traverse the range
[left, right]within the tree. - Aggregate the maximum values as you traverse segments.
- Traverse the range
Code
| |
| |
Complexity
- ⏰ Time complexity
- Tree Build:
O(n)(populate leaves and compute internal nodes). - Update:
O(log n)(move up the tree for updates). - Query:
O(log n)(traverse log levels in the tree).
- Tree Build:
- 🧺 Space complexity:
O(n)