Problem statement
Given an array[] named as input of size n, the array contains n integers along with an array we are given a value of X and Q. The task is to perform some operations on the array for Q queries. The task is given below:-
- (1, S, E): If the query is of type 1, then find the count of X in the range [S, E] inclusive where S is Starting index and E is the ending index of the array for the given range.
- (2, I, K): If the query is of type 2, then update the array element at index I to K.
Example 1
Input
Input array = {4, 0, 0, 1, 2, 0, 5, 0, 3 }
Q = 5
X = 0
Queries array = { { 1, 0, 3 },
{ 2, 4, 0 },
{ 1, 0, 8 },
{ 2, 8, 0 },
{ 1, 0, 8 } };
Output
2
5
6
Explanation
Following are the values of queries performed:
Query 1: Find count of X that is 0 in the range [0, 3], Count of Xs in the Array for a given range [0, 3] is 2
Query 2: Update input[4] to 0
Query 3: Find count of x that is 0 in the range [0, 8], Count of Xs in the Array for a given range [0, 8] is 5
Query 4: Update input[8] to 0, which will increase the count of 0 in the range [0, 8]
Query 5: Find count of x that is 0 in the range [0, 8] , Count of Xs in the Array for a given range [0, 8] is 6
Also see, Euclid GCD Algorithm
Naive Approach
The simplest brute force way to solve the problem is to modify the array element for the second type of query and traverse the array over the range [L, R] and output the count of K in it for the first type of query.
Code:
#include <bits/stdc++.h>
using namespace std;
// Perform all the queries
void performQueries(int size, int Q, int X ,vector<int>& input,vector<vector<int> >& queries)
{
for (int i = 1; i <= Q; i++) {
// Stores the count of Xs
int count = 0;
// Total of Count the number for query 1
if (queries[i - 1][0] == 1) {
for (int j = queries[i - 1][1];j <= queries[i - 1][2]; j++) {
if (input[j] == X)
count++;
}
cout << count << endl;
}
// Update the element for query 2
else {
input[queries[i - 1][1]] = queries[i - 1][2];
}
}
}
//Main Code
int main()
{
vector<int> input = { 4,0,0,1,2,0,5,0,3 };
int Q = 5;
vector<vector<int> > queries
= { { 1, 0,3 },
{ 2, 4, 0 },
{ 1, 0, 8 },
{ 2, 8, 0 },
{ 1, 0, 8 } };
int size = input.size();
int X = 0;
performQueries(size, Q, X, input, queries);
return 0;
}
Output:
|
Time Complexity
O(Q * N)
The time complexity to find the Count of Xs in the Array for a given range of indices after array updates for Q queries using naive approach will cost O(Q * N) time complexity where N is the size of the Array, and Q is the number of queries. Since for every query, we are iterating in the entire range and in worst case range could be from 0th index to the last index so using naive approach it will cost quadratic time complexity.
Space Complexity
O(1)
The space complexity to find the Count of Xs in the Array for a given range of indices after array updates for Q queries using a naive approach will cost no space complexity since we have not used any extra space in the entire implementation.