# Find the number of different numbers in the array after applying the given operation q times in C++

In this problem, we are given a number N which is the size of an array consisting of all zeros and Q queries each of the following type −

update(s, e, val ) -> this query will update all elements from s to e (both inclusive) to val.

Our task is to find the number of different numbers in the array after applying the given operation q times

Let’s take an example to understand the problem,

Input : N = 6, Q = 2
Q1 = update(1, 4, 3)
Q2 = update(0, 2, 4)

Output : 2

## Explanation

Initial array, arr[] = {0, 0, 0, 0, 0, 0}

Query 1 − update(1, 4, 3) -> arr[] = {0, 3, 3, 3, 3, 0}

Query 2 − update(0, 2, 4) -> arr[] = {4, 4, 4, 3, 3, 0}

## Solution Approach

A simple solution to the problem is by performing each query on the array and then counting the number of unique values in the array and using an extra array. And then return the count of unique array.

This solution is good but a more efficient solution to the problem is by using the concept of lazy propagation to optimise the range operation performed in the query. We will use the lazy propagation call to the query operation to find the number of unique numbers in the array. For this we will take a segment tree and update nodes when the operation is executed and initializing the tree with 0, values that are updating on operation returns the desired value. Here is the program which will elaborate the solution better.

## Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
#define N 100005
int lazyST[4 * N];
set<int> diffNo;
void update(int s, int e, int val, int idx, int l, int r){
if (s >= r or l >= e)
return;
if (s <= l && r <= e) {
lazyST[idx] = val;
return;
}
int mid = (l + r) / 2;
if (lazyST[idx])
lazyST[2 * idx] = lazyST[2 * idx + 1] = lazyST[idx];
lazyST[idx] = 0;
update(s, e, val, 2 * idx, l, mid);
update(s, e, val, 2 * idx + 1, mid, r);
}
void query(int idx, int l, int r){
if (lazyST[idx]) {
diffNo.insert(lazyST[idx]);
return;
}
if (r - l < 2)
return;
int mid = (l + r) / 2;
query(2 * idx, l, mid);
query(2 * idx + 1, mid, r);
}
int main() {
int n = 6, q = 3;
update(1, 3, 5, 1, 0, n);
update(4, 5, 1, 1, 0, n);
update(0, 2, 9, 1, 0, n);
query(1, 0, n);
cout<<"The number of different numbers in the array after operation is "<<diffNo.size();
return 0;
}

## Output

The number of different numbers in the array after operation is 3