Open In App

Array Range Queries to count Powerful numbers with updates

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of N integers, the task is to perform the following two operations on the given array: 
 

query(L, R): Print the number of Powerful numbers in the subarray from L to R. 
update(i, x) : update the value at index i to x, i.e arr[i] = x 
 


A number N is said to be Powerful Number if, for every prime factor p of it, p2 also divides it.
Prerequisites: Powerful Number, Segment tree
Examples: 
 

Input: 
arr = {1, 12, 3, 8, 17, 9} 
Query 1: query(L = 1, R = 4) 
Query 2: update(i = 1, x = 9) 
Query 3: query(L = 1, R = 4) 
Output: 


Explanation: 
Query 1: Powerful numbers in range arr[1:4] is 8. 
Query 2: Powerful numbers in range arr[1:4] after update operation is 9 and 8. 
 


 


Approach:
Since we need to handle point updates and range queries so we will use a segment tree to solve the problem. 
 

  1. We will precompute all the Powerful numbers till the maximum value that arr[i] can take, say MAX
    The time complexity of this operation will be O(MAX * sqrt(MAX)) 
     
  2. Building the segment tree: 
    • The problem can be reduced to subarray sum using segment tree
       
    • Now we can build the segment tree where the leaf nodes will represent 1(when a number is a Powerful number) or 0(when a number is not a powerful number). All the internal nodes will have the sum of both of its children. 
       
  3. Point Updates: 
    • To update an element we need to look at the interval in which the element is and recurse accordingly on the left or the right child. If the element to be updated is a Powerful number then we update the leaf as 1, else 0. 
       
  4. Range Query: 
    • Whenever we get a query from L to R, then we can query the segment tree for the sum of nodes in range L to R, which in turn represents the number of Powerful numbers in the range L to R. 
       


Below is the implementation of the above approach: 
 

C++
Java Python3 C# JavaScript

Output: 
Number of Powerful numbers between 0 to 3 = 2
Number of Powerful numbers between 0 to 3 = 3

 

Time Complexity: O(logN) per query
Space Complexity:  O(MAX*log2MAX). This is because the size of the segment tree used in the program is 3 times the value of MAX, and the maximum height of the segment tree is log2(MAX)+1. Therefore, the total space used by the segment tree is 3 times the value of MAX multiplied by the maximum height of the segment tree, which is O(MAX log2MAX).

In addition to the segment tree, the program also uses three arrays: arr, powerful, and tree. The size of arr and powerful is MAX, and the size of tree is 3 times MAX. Therefore, the total space used by these arrays is O(MAX).


Explore