Find Value after performing Increment Decrement queries
Last Updated :
21 Jul, 2022
Given a variable X having an initial value 0 and an array of queries Q[] of size N containing the type of operations, the task is to return the value of N after performing all the below operations:
- Type-1: Increment the value of X by 1.
- Type-2: Decrement the value of X by 1.
Examples:
Input: Q = {2, 1, 1}
Output: 1
Explanation: The operations are performed as follow:
Initially, X = 0,
Query 1(Type 2): X is decremented by 1, X = 0 – 1 = -1
Query 2(Type 1): X is incremented by 1, X = -1 + 1 = 0
Query 3(Type 1): X is incremented by 1, X = 0 + 1 = 1
Hence, the output will be 1
Input: Q = {1, 1, 1}
Output: 3
Approach: To solve the problem follow the below idea:
- Traverse the given array of Queries.
- Whenever the array element is 1, increment N by 1, and
- Whenever the array element is 2, decrement N by 1.
- Return the final value of N as the required answer.
Below is the implementation for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findvalue(vector< int >& queries)
{
int n = queries.size();
int x = 0;
for ( int i = 0; i < n; i++) {
if (queries[i] == 1) {
x = x + 1;
}
else {
x = x - 1;
}
}
return x;
}
int main()
{
vector< int > queries = { 2, 1, 1 };
int ans = findvalue(queries);
cout << ans;
return 0;
}
|
Java
public class GFG {
static int findvalue( int []queries)
{
int n = queries.length;
int x = 0 ;
for ( int i = 0 ; i < n; i++) {
if (queries[i] == 1 ) {
x = x + 1 ;
}
else {
x = x - 1 ;
}
}
return x;
}
public static void main(String[] args)
{
int []queries = { 2 , 1 , 1 };
int ans = findvalue(queries);
System.out.println(ans);
}
}
|
Python3
def findvalue(queries) :
n = len (queries);
x = 0 ;
for i in range (n) :
if (queries[i] = = 1 ) :
x = x + 1 ;
else :
x = x - 1 ;
return x;
if __name__ = = "__main__" :
queries = [ 2 , 1 , 1 ];
ans = findvalue(queries);
print (ans);
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int findvalue(List< int > queries)
{
int n = queries.Count;
int x = 0;
for ( int i = 0; i < n; i++) {
if (queries[i] == 1) {
x = x + 1;
}
else {
x = x - 1;
}
}
return x;
}
public static void Main( string [] args)
{
List< int > queries = new List< int >{ 2, 1, 1 };
int ans = findvalue(queries);
Console.Write(ans);
}
}
|
Javascript
<script>
function findvalue( queries)
{
let n = queries.length;
let x = 0;
for (let i = 0; i < n; i++) {
if (queries[i] == 1) {
x = x + 1;
}
else {
x = x - 1;
}
}
return x;
}
let queries = [ 2, 1, 1 ];
let ans = findvalue(queries);
document.write(ans);
</script>
|
Time Complexity: O(N).
Auxiliary Space: O(1).
Share your thoughts in the comments
Please Login to comment...