Fenwick Tree
You are given an array/list 'ARR' of ‘N’ integers, and ‘Q’ queries. Each query can be of two types:
Given 2 integers ‘L’,’R’ ( L>=0 and R<N ) find the sum of all the elements of the array with the index in the range 'L' and 'R' (inclusive). This is a query of type range sum.
Given an index ‘i’ update the value of ARR[i] to a given integer ‘X’. This is a query of type point update.
Your task is to perform the queries on the given array and return the desired output for each query.
Input format :
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains a single integer ‘N’ denoting the number of elements in the array.
The second line of each test case contains ‘N’ space-separated integers denoting the array ‘ARR’.
The third line of each test case contains an integer ‘Q’ denoting the number of queries.
The next ‘Q’ lines of each test case contain 3 space-separated integers denoting the following:
1. The first integer denotes the type of query. It can be either a ‘1’ or a ‘2’. 1 denotes range sum type query and 2 denotes update type query.
2. If the query is of the first type, the second and third integers on the same line denote ‘L’ and ‘R’ respectively which are the range of which we need to calculate its sum.
3. If the query of the second type, the second integer denotes ‘i’ the index of which the value is to be updated and the third integer denotes ‘X’ the updated value of the ‘i-th’ index.
Output format :
For each query of the first type, print the sum of values with indices in the range of ‘L’ and ‘R’.
For queries of the second type, do not print anything just update the value in the given array.
Note:
You don't need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10^5
1 <= Q <= 10^5
-10^9 <= ARR[i] <= 10^9
Where ‘N’ denotes the length of the array 'ARR', 'Q' denotes the number of queries, and ‘ARR[i]’ is the value of the element at index ‘i’.
Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force Approach
- The key idea of the approach is to process the queries as asked. i.e If range sum is asked we do a range sum using a loop and update the values in the array if it is an update quer...read more
CodingNinjas
author
2y
Fenwick Tree Approach
The idea is to do the given queries efficiently. We can do this in many different ways. One of them is using a Fenwick tree or a binary indexed tree.
- The key idea of a Fenwick tre...read more
Help your peers!
Add answer anonymously...
Top Goldman Sachs Software Analyst interview questions & answers
Popular interview questions of Software Analyst
>
Goldman Sachs Software Analyst Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app