Print the Array of size N containing values in range [0, M) after Q query updates
Given array arr[] of size N containing cyclic variables having states from 0 to (M – 1) (i.e when incremented from M-1 it goes to 0). The task is to fulfill the Q queries of which are of any of the following two types:
- 1st Type: 1 L R K – increment all the values in range of indices [L, R], K times cyclically.
- 2nd Type: 2 L R – print the updated values in range of indices [L, R].
Examples:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input: arr[] = {2, 2, 7, 2, 5}, Q = 5, M = 8
queries[][] = {{1, 0, 3, 4},
{1, 4, 4, 2},
{1, 0, 0, 7},
{2, 1, 3},
{2, 3, 3}}
Output: {6, 3, 6}, {6}
Explanation: The states after performing each operation are:
After 1st: {6, 6, 3, 6, 5}
After 2nd: {6, 6, 3, 6, 7}
After 3rd: {5, 6, 3, 6, 7}
So in 4th query elements from index 1 to 3 and in 5th query element in index 3 are printed.Input: arr[] = [2, 3, 4, 5], Q = 3, M = 6
queries[][] = {{1, 0, 0, 3},
{1, 1, 2, 2},
{1, 3, 3, 1},
{2, 0, 3}}
Output: {5, 5, 1, 1}
Approach: The problem can be solved using greedy approach. Follow the steps mentioned below to implement the approach:
- When a query is of first type update all the values in range [L, R], K times.
- When a query is of second type then print the value in range [L, R].
Below is the implementation of the above approach.
C++14
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to implement the queriesvoid update(int arr[], int N, int M, int Q, vector<vector<int> >& queries){ // Loop to implement the queries for (int i = 0; i < Q; i++) { if (queries[i][0] == 1) { for (int j = queries[i][1]; j <= queries[i][2]; j++) arr[j] = (arr[j] + queries[i][3]) % M; } else if (queries[i][0] == 2) { for (int j = queries[i][1]; j <= queries[i][2]; j++) cout << arr[j] << " "; cout << endl; } }} // Driver's codeint main(){ int N = 5, M = 8, Q = 5; int arr[] = { 2, 2, 7, 2, 5 }; vector<vector<int> > queries(Q); queries[0] = { 1, 0, 3, 4 }; queries[1] = { 1, 4, 4, 2 }; queries[2] = { 1, 0, 0, 7 }; queries[3] = { 2, 1, 3 }; queries[4] = { 2, 3, 3 }; update(arr, N, M, Q, queries); return 0;} |
6 3 6 6
Time Complexity: O(Q*N)
Auxiliary Space: O(1)

