![]() |
VOOZH | about |
Given an array arr[] of size n and a list of Q queries, where each query is of two types:
Return a list of results for all Type 2 queries after performing all the queries sequentially.
Examples:
Input: arr[] = {2, 3, 4, 6, 8, 16}, queries[] = {{2, 0, 2}, {1, 3, 8}, {2, 2, 5}}
Output: [12, 16]
Explanation: The queries are processed sequentially, updating the array when required.
{2, 0, 2} --> lcm of all numbers within the given range: LCM of [2, 3, 4] = 12
{1, 3, 8} --> update the value at a specified index: array becomes [2, 3, 4, 8, 8, 16]
{2, 2, 5} --> lcm of all numbers within the given range: LCM of [4, 8, 8, 16] = 16Input: arr[] = {1, 2, 3, 4}, query[] = {{2, 0, 3}, {1, 0, 5}, {2, 0, 1}}
Output: [12, 10]
Explanation: The queries are processed sequentially, updating the array when required.
{2, 0, 3} --> lcm of all numbers within the given range: LCM of [1, 2, 3, 4] = 12
{1, 0, 5} --> update the value at a specified index: array becomes [5, 2, 3, 4]
{2, 0, 1} --> lcm of all numbers within the given range: LCM of [5, 2] = 10
Table of Content
The idea is to process each query one by one in a brute-force manner. For an update query, we directly modify the array at the given index. For a range query, we iterate through the given range and keep taking LCM cumulatively, using the property that
LCM(a, b)can be computed via GCD.The above approach is based on the following mathematical idea.
Mathematically, LCM(l, r) = LCM(arr[l], arr[l+1] , . . . ,arr[r-1], arr[r]) and
LCM(a, b) = (a*b) / GCD(a,b)
12 16
Time Complexity: O(q * n * log(min(a, b)))
Auxiliary Space: O(1) since we are only storing a few integers at a time. The space used by the input arr and queries is not considered.
The idea is to use a Segment Tree to efficiently handle range LCM queries and updates. Instead of recomputing LCM for every query from scratch, we build a tree where each node stores the LCM of a segment of the array. This allows us to answer any range query by combining only the relevant segments (using LCM), and updates are handled by modifying a single element and updating only the affected nodes in the tree.
12 16
Time Complexity: O(n + q * log(n) * log(min(a, b)))
Auxiliary Space: O(n)