# Array range queries to find the number of perfect square elements with updates

Given an array arr[] of N integers, the task is to perform the following two queries:

• query(start, end): Print the number of perfect square numbers in the sub-array from start to end
• update(i, x): Add x to the array element referenced by array index i, that is: arr[i] = x

Note: 0 based indexing is followed in the below example.

Example:

Input: arr = [ 16, 15, 8, 9, 14, 25 ];
Query 1: query(start = 0, end = 4)
Query 2: update(i = 3, x = 11) i.e. arr=11
Query 3: query(start = 0, end = 4)
Output: 2 1
Explanation:
In Query 1, the sub-array [0…4] has 2 perfect square numbers 16 and 9 viz. [ 16, 15, 8, 9, 14 ]
In Query 2, the value at index 3 is updated to 11,
the array arr now is, [ 16, 15, 8, 11, 14, 25 ]
In Query 3, the sub-array [0…4] has 1 perfect square number 16 viz. [ 16, 15, 8, 11, 14 ]

Approach:

To handle both point updates and range queries, a segment tree is optimal for this purpose.
In order to check for perfect square numbers, the idea is to first compute the square root of the number and if the square root is an integer then the current element is a perfect square otherwise not. If the current element is a perfect square, then set it to 1 else to 0.

Building the segment tree:

• The problem is now reduced to the subarray sum using segment tree problem.
• Now, we can build the segment tree where a leaf node is represented as either 0 (if it is not an perfect square number) or 1 (if it is perfect square number).
• The internal nodes of the segment tree equal to the sum of its child nodes, thus a node represent the total perfect square numbers in the range from L to R with range [L, R] falling under this node and the sub-tree underneath it.

• Whenever we receive a query from beginning to end, we can query the segment tree for the sum of nodes in range from start to end, which in turn represent the number of perfect square numbers in the range start to end.

• To perform a point update and to update the value at index i to x, we check for the following cases:
Let the old value of arr[i] be y and the new value be x.
1. Case 1: If x and y both are perfect square numbers
Count of perfect square numbers in the subarray does not change so we just update array and do not modify the segment tree
2. Case 2: If x and y both are not perfect square numbers
Count of perfect square numbers in the subarray does not change so we just update array and do not modify the segment tree
3. Case 3: If y is a perfect square number but x is not
Count of perfect square numbers in the subarray decreases so we update array and add -1 to every range. The index i which is to be updated is a part of in the segment tree
4. Case 4: If y is not an perfect square number but x is an perfect square number
Count of perfect square numbers in the subarray increases so we update array and add 1 to every range. The index i which is to be updated is a part of in the segment tree

Below is the implementation of the above approach:

## C++

 `// C++ program to find number of ` `// perfect square numbers in a ` `// subarray and performing updates ` ` `  `#include ` `using` `namespace` `std; ` ` `  `#define MAX 1000 ` ` `  `// Function to check if a number is ` `// a perfect square or not ` `bool` `isPerfectSquare(``long` `long` `int` `x) ` `{ ` `    ``// Find floating point value of ` `    ``// square root of x. ` `    ``long` `double` `sr = ``sqrt``(x); ` ` `  `    ``// If square root is an integer ` `    ``return` `((sr - ``floor``(sr)) == 0) ` `               ``? ``true` `               ``: ``false``; ` `} ` ` `  `// A utility function to get the middle ` `// index from corner indexes. ` `int` `getMid(``int` `s, ``int` `e) ` `{ ` `    ``return` `s + (e - s) / 2; ` `} ` ` `  `// Recursive function to get the number ` `// of perfect square numbers in a given ` `// range ` `/* where ` `  ``st    --> Pointer to segment tree ` `  ``index --> Index of current node in the ` `            ``segment tree. Initially 0 is  ` `            ``passed as root is always  ` `            ``at index 0 ` `  ``ss & se  --> Starting and ending indexes  ` `              ``of the segment represented by  ` `              ``current node i.e. st[index] ` `  ``qs & qe  --> Starting and ending indexes ` `               ``of query range   */` `int` `queryUtil(``int``* st, ``int` `ss, ` `              ``int` `se, ``int` `qs, ` `              ``int` `qe, ``int` `index) ` `{ ` `    ``// If segment of this node is a part ` `    ``// of given range, then return ` `    ``// the number of perfect square numbers ` `    ``// in the segment ` `    ``if` `(qs <= ss && qe >= se) ` `        ``return` `st[index]; ` ` `  `    ``// If segment of this node ` `    ``// is outside the given range ` `    ``if` `(se < qs || ss > qe) ` `        ``return` `0; ` ` `  `    ``// If a part of this segment ` `    ``// overlaps with the given range ` `    ``int` `mid = getMid(ss, se); ` `    ``return` `queryUtil(st, ss, mid, qs, ` `                     ``qe, 2 * index + 1) ` `           ``+ queryUtil(st, mid + 1, se, ` `                       ``qs, qe, 2 * index + 2); ` `} ` ` `  `// Recursive function to update ` `// the nodes which have the given ` `// index in their range. ` `/* where ` `   ``st, si, ss & se are same as getSumUtil() ` `   ``i --> index of the element to be updated.  ` `         ``This index is in input array. ` `   ``diff --> Value to be added to all nodes ` `          ``which have i in range  ` `*/` `void` `updateValueUtil(``int``* st, ``int` `ss, ` `                     ``int` `se, ``int` `i, ` `                     ``int` `diff, ``int` `si) ` `{ ` `    ``// Base Case: ` `    ``// If the input index lies outside ` `    ``// the range of this segment ` `    ``if` `(i < ss || i > se) ` `        ``return``; ` ` `  `    ``// If the input index is in range ` `    ``// of this node, then update the value ` `    ``// of the node and its children ` `    ``st[si] = st[si] + diff; ` `    ``if` `(se != ss) { ` ` `  `        ``int` `mid = getMid(ss, se); ` `        ``updateValueUtil(st, ss, mid, i, ` `                        ``diff, 2 * si + 1); ` `        ``updateValueUtil(st, mid + 1, se, ` `                        ``i, diff, 2 * si + 2); ` `    ``} ` `} ` ` `  `// Function to update a value in the ` `// input array and segment tree. ` `// It uses updateValueUtil() to update ` `// the value in segment tree ` `void` `updateValue(``int` `arr[], ``int``* st, ` `                 ``int` `n, ``int` `i, ` `                 ``int` `new_val) ` `{ ` `    ``// Check for erroneous input index ` `    ``if` `(i < 0 || i > n - 1) { ` `        ``printf``(``"Invalid Input"``); ` `        ``return``; ` `    ``} ` ` `  `    ``int` `diff, oldValue; ` ` `  `    ``oldValue = arr[i]; ` ` `  `    ``// Update the value in array ` `    ``arr[i] = new_val; ` ` `  `    ``// Case 1: Old and new values ` `    ``// both are perfect square numbers ` `    ``if` `(isPerfectSquare(oldValue) ` `        ``&& isPerfectSquare(new_val)) ` `        ``return``; ` ` `  `    ``// Case 2: Old and new values ` `    ``// both not perfect square numbers ` `    ``if` `(!isPerfectSquare(oldValue) ` `        ``&& !isPerfectSquare(new_val)) ` `        ``return``; ` ` `  `    ``// Case 3: Old value was perfect square, ` `    ``// new value is not a perfect square ` `    ``if` `(isPerfectSquare(oldValue) ` `        ``&& !isPerfectSquare(new_val)) { ` `        ``diff = -1; ` `    ``} ` ` `  `    ``// Case 4: Old value was ` `    ``// non-perfect square, ` `    ``// new_val is perfect square ` `    ``if` `(!isPerfectSquare(oldValue) ` `        ``&& !isPerfectSquare(new_val)) { ` `        ``diff = 1; ` `    ``} ` ` `  `    ``// Update values of nodes in segment tree ` `    ``updateValueUtil(st, 0, n - 1, i, diff, 0); ` `} ` ` `  `// Return no. of perfect square numbers ` `// in range from index qs (query start) ` `// to qe (query end). ` `// It mainly uses queryUtil() ` `void` `query(``int``* st, ``int` `n, ` `           ``int` `qs, ``int` `qe) ` `{ ` ` `  `    ``int` `perfectSquareInRange ` `        ``= queryUtil( ` `            ``st, 0, n - 1, qs, qe, 0); ` ` `  `    ``cout << perfectSquareInRange << ``"\n"``; ` `} ` ` `  `// Recursive function that constructs ` `// Segment Tree for array[ss..se]. ` `// si is index of current node ` `// in segment tree st ` `int` `constructSTUtil(``int` `arr[], ``int` `ss, ` `                    ``int` `se, ``int``* st, ` `                    ``int` `si) ` `{ ` `    ``// If there is one element in array, ` `    ``// check if it is perfect square number ` `    ``// then store 1 in the segment tree ` `    ``// else store 0 and return ` `    ``if` `(ss == se) { ` ` `  `        ``// if arr[ss] is a perfect ` `        ``// square number ` `        ``if` `(isPerfectSquare(arr[ss])) ` `            ``st[si] = 1; ` `        ``else` `            ``st[si] = 0; ` ` `  `        ``return` `st[si]; ` `    ``} ` ` `  `    ``// If there are more than one ` `    ``// elements, then recur for ` `    ``// left and right subtrees ` `    ``// and store the sum of the ` `    ``// two values in this node ` `    ``int` `mid = getMid(ss, se); ` `    ``st[si] ` `        ``= constructSTUtil(arr, ss, ` `                          ``mid, st, si * 2 + 1) ` `          ``+ constructSTUtil(arr, mid + 1, ` `                            ``se, st, si * 2 + 2); ` `    ``return` `st[si]; ` `} ` ` `  `// Function to construct a segment ` `// tree from given array. This ` `// function allocates memory for ` `// segment tree and calls ` `// constructSTUtil() to fill ` `// the allocated memory ` `int``* constructST(``int` `arr[], ``int` `n) ` `{ ` ` `  `    ``// Allocate memory for segment tree ` `    ``// Height of segment tree ` `    ``int` `x = (``int``)(``ceil``(log2(n))); ` ` `  `    ``// Maximum size of segment tree ` `    ``int` `max_size = 2 * (``int``)``pow``(2, x) - 1; ` ` `  `    ``int``* st = ``new` `int``[max_size]; ` ` `  `    ``// Fill the allocated memory st ` `    ``constructSTUtil(arr, 0, n - 1, st, 0); ` ` `  `    ``// Return the constructed segment tree ` `    ``return` `st; ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``int` `arr[] = { 16, 15, 8, 9, 14, 25 }; ` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr); ` ` `  `    ``// Build segment tree from given array ` `    ``int``* st = constructST(arr, n); ` ` `  `    ``// Query 1: Query(start = 0, end = 4) ` `    ``int` `start = 0; ` `    ``int` `end = 4; ` `    ``query(st, n, start, end); ` ` `  `    ``// Query 2: Update(i = 3, x = 11), ` `    ``// i.e Update a[i] to x ` `    ``int` `i = 3; ` `    ``int` `x = 11; ` `    ``updateValue(arr, st, n, i, x); ` ` `  `    ``// uncomment to see array after update ` `    ``// for(int i = 0; i < n; i++) ` `    ``// cout << arr[i] << " "; ` ` `  `    ``// Query 3: Query(start = 0, end = 4) ` `    ``start = 0; ` `    ``end = 4; ` `    ``query(st, n, start, end); ` ` `  `    ``return` `0; ` `} `

Output:

```2
1
```

Time Complexity: The time complexity of each query and update is O(log N) and that of building the segment tree is O(N) My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.