![]() |
VOOZH | about |
Akku has solved many problems, she is a genius. One day her friend gave her an Array of sizes n and asked her to perform some queries of the following type:
Each query consists of three integers
1 A B: Update the Array at index A by value B
2 A B: if the subarray from index A to B (both inclusive) is
Akku needs your help, can you help her?
Example:
Input: nums = {1,5,7,4,3,5,9}, queries = {{2,1,3},{1,7,4},{2,6,7}}
Output: {0,1}
Explanation:
For the 1st query given : A = 1, B = 3. From 1 to 3(1,5,7) elements are in increasing order. So answer is 0.
For the 2nd query we have to update the 7th element of the array by 4. So new updated array will be {1,5,7,4,3,5,4}
For the 3rd query A = 6, B = 7. From 6 to 7 (5, 4) elements are in descending order. So answer is 1.Input: nums = {3, 2, 5, 4, 7, 1, 6}, queries = {{2, 1, 3}, {1, 4, 6}, {2, 2, 5}, {1, 3, 8}}
Output: {-1, 0}
Approach:
The idea is to use a segment tree data structure to store information about the subarrays of the given array. Each node of the segment tree represents a subarray and has four attributes: dec, inc, lm, and rm. These attributes indicate whether the subarray is decreasing, increasing, the leftmost and rightmost elements of the subarray respectively.
We are going to use the below function to execute our logic:
We'll use two functions: merge() and update(). The merge function takes two nodes of the segment tree and returns a new node that represents the merged subarray of the two nodes. The update function modifies the segment tree by changing the value of a given index in the array and updating the nodes affected by the change.
We'll also use a function called query() that takes a range of indices and returns the node that represents the subarray in that range. The function uses the merge function to combine the nodes that cover the range in the segment tree.
We'll also use a function called solveQueries() that takes the array and the queries as input and returns a vector of integers as output. Iterates over the queries and performs the appropriate operation based on the query type.
- For query type 1, it calls the update function to change the value of the array at a given index.
- For query type 2, it calls the query function to get the node for the given range and then checks the attributes of the node to determine the answer.
The answer is -1 if the subarray is neither increasing nor decreasing, 0 if it is only increasing, 1 if it is only decreasing, and -1 if it is both increasing and decreasing. Finally, pushes the answer to the output vector and returns it at the end.
Steps:
Below is the implementation of the above approach:
Result: 0 1
Time Complexity: O(N+QlogN), where N is the size of the input array, and Q is the number of queries.
Auxiliary Space: O(N)