GFG App
Open App
Browser
Continue

# Count elements remained same after applying the given operations

Given an array X[]. By using the given operation, you need to return the number of elements having the same initial value except 1 and 2 after applying the given operations after infinite time.

• If at any indices 1 or 2 is present, Then after each second the elements, which are adjacent to them are increased by 1 or 2 linearly in both directions.
• The value of an element will remain unchanged If it is an increment from both sides at the same time by 1 and 2.
• If 1 and 2 are adjacent, They can’t increment, Only the elements except 1 and 2 can be incremented.
• The increment process in that direction is stopped If both 1 and 2 try to increment the same element or no element is there for incrementing. For Example: In the below image in operation 2, 6 is being incremented by both 1 and 2. 6 will remain the same, and the linearly incrementing process by 1 on the right side and 2 on the left side stops.

For more clarification, the operations are defined with the help of a graphical representation.

Explanation of operations

Examples:

Input: N = 9, X[] = {1, 3, 2, 4, 5, 3, 7, 8, 1}
Output: 2
Explanation: The operations take place as:

• After 1 Second: X[ 2 ] = 3, which is adjacent to both 1 and 2. So, X[ 2 ] remains the same. X[ 4 ] = 4 is adjacent to 2, Hence incremented by 2. A[ 8 ] = 8, is adjacent to 1, hence incremented by 1. So updated X[] is = { 1, 3, 2, 6, 5, 3, 7, 9, 1}
• After 2 Second: Updated X[] after 1 second is = { 1, 3, 2, 6, 5, 3, 7, 9, 1}. Now X[ 5 ] = 5 and X[ 7 ] = 7 will be incremented by 2 and 1 at X[ 3 ] and X[9]. So the updated X[] becomes: { 1, 3, 2, 6, 7, 3, 8, 9, 1}
• After 3 Second: Updated X[] after 2 seconds is = { 1, 3, 2, 6, 7, 3, 8, 9, 1} Now X[ 6 ] = 3 will be incremented by 2 and 1 at the same time. So it will remain unchanged, then updated X[] becomes: { 1, 3, 2, 6, 7, 3, 8, 9, 1}.
• There are a total of 2 elements X[2] and X[ 6 ], Which remain the same as the initial value except 1 and 2. Therefore, the output is 2.

Input: N = 9, X[] = { 1, 2, 1, 4, 3, 4, 2, 2, 1}
Output: 1
Explanation: It can be verified that after infinite time, there will be only 1 unchanged element, which will be X[ 5 ] = 3. Therefore, the output is 1.

Approach: Implement the idea below to solve the problem

The problem is Greedy logic based and can be solved by using some mathematics. For more clarification see the Concept of approach section.

Concept of approach:

It is clear from the statement that, We have to output the number of elements. Which will remain the same as their initial value after performing the given operations an infinite number of times. Those elements will remain the same if they are being forced by incrementing their values by 1 and 2 from both sides at the same time.

So, the first observation comes that, They will lie in between somewhere elements 1 and 2.

Now it can be two cases:

• The number of elements between 1 and 2 is even: In this case, there will no element, which will remain the same after performing the given operation an infinite number of times.
• For example: X[] = {1, 3, 4, 5, 6, 2}
• After 1 second: 3 is incremented by 1 and 6 in incremented by 2. Then X[] = {1, 4, 4, 5, 8, 2}
• After 2 seconds: 4 is incremented by 1 and 5 in incremented by 2. Then X[] = {1, 4, 5, 7, 8, 2}
• Now, no element is there such that it has same value after performing the operation except 1 and 2. So from here observation comes that no element will remain same, If there are even number of elements are present between 1 and 2.
• The number of elements between 1 and 2 are odd: In this case there will certainly one element, which will remain same after performing the given operation for infinite number of times.
• For example: X[] = {1 3, 4, 3, 5, 6, 2}
• After 1 second: 3 is incremented by 1 and 6 in incremented by 2. Then X[] = {1 4, 4, 3, 5, 8, 2}
• After 2 seconds: 4 is incremented by 1 and 5 in incremented by 2. Then X[] = {1 4, 5, 3, 7, 8, 2}
• Now, 3 which is present in middle between 1 and 2 is being forced by increment its value by 1 and 2 from both sides. So, 3 remain same, because of second condition of the problem statement
• Thus the observation comes that, if there are odd number of elements present in between 1 and 2, Then there will certainly one element, Which will remain same as its initial value.

Steps were taken to solve the problem:

• Create two ArrayList<Integer> let’s say Indices and Values.
• Create ans variable for holding the answer.
•  Run a for loop from i = 0 to i < N and follow the below-mentioned steps under the scope of the loop:
• if ( X[ i ] == 1 || X[ i ] == 2 )
• Values.add( X[ i ] )
• If the size of any ArrayList is zero, then ans will be equal to N.
• else:
• Run a loop for i =1 to i < values.size() and follow the below-mentioned steps under the scope of the loop:
•  if (values.get( i ) != values.get(i – 1)
• Create a variable, X.
• X = indices.get( i ) – indices.get(i – 1)
• X = X – 1
• If (X is odd), Then ans++.
• Output the value of ans.

Below is the code to implement the approach:

## C++

 `// C++ code to implement the approach`   `#include ` `using` `namespace` `std;`   `// Method for printing unchanged elements` `void` `UnchangedElements(``int` `N, ``int` `X[])` `{` `    ``// vector for storing indices` `    ``// of 1 and 2 So the we can` `    ``// calculate number of elements` `    ``// between them` `    ``vector<``int``> indices;`   `    ``// ArrayList for storing 1 and 2,` `    ``// So that we can know different 1` `    ``// and 2 are adjacents like {1, 1},` `    ``// {2, 2} are not different` `    ``// adjacents but {1, 2}, {2, 1}` `    ``// are different adjacents` `    ``vector<``int``> values;`   `    ``// Loop for traversing over X[] and` `    ``// initialize the both ArrayList` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``// Condition when 1 and 2` `        ``// found at any index` `        ``if` `(X[i] == 1 || X[i] == 2) {`   `            ``// Adding indices and` `            ``// values to ArrayLists` `            ``values.push_back(X[i]);` `            ``indices.push_back(i);` `        ``}` `    ``}`   `    ``// ans variable to hold number of` `    ``// unchanged elements` `    ``long` `long` `ans = 0;`   `    ``// Boolean flag is initialized` `    ``// as false` `    ``bool` `flag = ``false``;`   `    ``// Condition, When no 1 and 2 are` `    ``// present in X[] So that values` `    ``// vector will by empty, As it` `    ``// is only initialized to store 1` `    ``// and 2, If there are no 1 and 2` `    ``// are present in X[] values` `    ``// vector will have zero size` `    ``if` `(values.size() == 0) {`   `        ``// This will execute if` `        ``// X[] doesn't contains 1 or 2` `        ``cout << N << endl;` `        ``flag = ``true``;` `    ``}`   `    ``// Loop for traversing` `    ``// over values vector` `    ``for` `(``int` `i = 1; i < values.size(); i++) {`   `        ``// If different adjacents are` `        ``// found like {2, 1} or {1, 2}` `        ``// in values vector` `        ``if` `(values[i] != values[i - 1]) {`   `            ``// Variable to hold the` `            ``// length or formally` `            ``// number of elements` `            ``// between {1, 2} or {2, 1}` `            ``long` `long` `x = indices[i] - indices[i - 1];` `            ``x -= 1;`   `            ``// if number of elements` `            ``// are odd, then incrementing` `            ``// ans variable by 1` `            ``if` `(x & 1) {` `                ``ans++;` `            ``}` `        ``}` `    ``}`   `    ``// This Print line will execute` `    ``// If at least once 1 or 2` `    ``// is present in X[]` `    ``if` `(flag != ``true``)` `        ``cout << ans << endl;` `}`   `int` `main()` `{`   `    ``// Inputs` `    ``int` `N = 9;` `    ``int` `X[] = { 1, 3, 2, 4, 5, 3, 7, 8, 1 };`   `    ``// Function call` `    ``UnchangedElements(N, X);` `}`

## Java

 `// Java code to implement the approach`   `import` `java.util.*;` `public` `class` `GFG {`   `    ``// Driver Function` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``// Inputs` `        ``int` `N = ``9``;` `        ``int` `X[] = { ``1``, ``3``, ``2``, ``4``, ``5``, ``3``, ``7``, ``8``, ``1` `};`   `        ``// Function call` `        ``UnchangedElements(N, X);` `    ``}`   `    ``// Method for printing unchanged elements` `    ``static` `void` `UnchangedElements(``int` `N, ``int``[] X)` `    ``{` `        ``// ArrayList for storing indices` `        ``// of 1 and 2 So the we can` `        ``// calculate number of elements` `        ``// between them` `        ``ArrayList indices = ``new` `ArrayList<>();`   `        ``// ArrayList for storing 1 and 2,` `        ``// So that we can know different 1` `        ``// and 2 are adjacents like {1, 1},` `        ``// {2, 2} are not different` `        ``// adjacents but {1, 2}, {2, 1}` `        ``// are different adjacents` `        ``ArrayList values = ``new` `ArrayList<>();`   `        ``// Loop for traversing over X[] and` `        ``// initialize the both ArrayList` `        ``for` `(``int` `i = ``0``; i < N; i++) {`   `            ``// Condition when 1 and 2` `            ``// found at any index` `            ``if` `(X[i] == ``1` `|| X[i] == ``2``) {`   `                ``// Adding indices and` `                ``// values to ArrayLists` `                ``values.add(X[i]);` `                ``indices.add(i);` `            ``}` `        ``}`   `        ``// ans variable to hold number of` `        ``// unchanged elements` `        ``long` `ans = ``0``;`   `        ``// Boolean flag is initialized` `        ``// as false` `        ``boolean` `flag = ``false``;`   `        ``// Condition, When no 1 and 2 are` `        ``// present in X[] So that values` `        ``// ArrayList will by empty, As it` `        ``// is only initialized to store 1` `        ``// and 2, If there are no 1 and 2` `        ``// are present in X[] values` `        ``// ArrayList will have zero size` `        ``if` `(values.size() == ``0``) {`   `            ``// This will execute if` `            ``// X[] doesn't contains 1 or 2` `            ``System.out.println(N);` `            ``flag = ``true``;` `        ``}`   `        ``// Loop for traversing` `        ``// over ArrayLists` `        ``for` `(``int` `i = ``1``; i < values.size(); i++) {`   `            ``// If different adjacents are` `            ``// found like {2, 1} or {1, 2}` `            ``// in values ArrayList` `            ``if` `(values.get(i) != values.get(i - ``1``)) {`   `                ``// Variable to hold the` `                ``// length or formally` `                ``// number of elements` `                ``// between {1, 2} or {2, 1}` `                ``long` `x` `                    ``= indices.get(i) - indices.get(i - ``1``);` `                ``x -= ``1``;`   `                ``// if number of elements` `                ``// are odd, then incrementing` `                ``// ans variable by 1` `                ``if` `((x & ``1``) == ``1``) {` `                    ``ans++;` `                ``}` `            ``}` `        ``}`   `        ``// This Print line will execute` `        ``// If at least once 1 or 2` `        ``// is present in X[]` `        ``if` `(flag != ``true``)` `            ``System.out.println(ans);` `    ``}` `}`

## Python3

 `# Python3 code to implement the approach`   `# Method for printing unchanged elements` `def` `unchanged_elements(N, X):` `    ``# List for storing indices of 1 and 2` `    ``# So that we can calculate number of elements between them` `    ``indices ``=` `[]` `    `  `    ``# List for storing 1 and 2,` `    ``# So that we can know different 1` `    ``# and 2 are adjacents like [1, 1],` `    ``# [2, 2] are not different` `    ``# adjacents but [1, 2], [2, 1]` `    ``# are different adjacents` `    ``values ``=` `[]` `    `  `    ``# Loop for traversing over X[] and` `    ``# initialize both lists` `    ``for` `i ``in` `range``(N):` `        ``# Condition when 1 and 2` `        ``# found at any index` `        ``if` `X[i] ``=``=` `1` `or` `X[i] ``=``=` `2``:` `            ``# Adding indices and` `            ``# values to lists` `            ``values.append(X[i])` `            ``indices.append(i)` `    `  `    ``# Variable to hold number of` `    ``# unchanged elements` `    ``ans ``=` `0` `    `  `    ``# Boolean flag is initialized` `    ``# as False` `    ``flag ``=` `False` `    `  `    ``# Condition, When no 1 and 2 are` `    ``# present in X[] So that values` `    ``# list will by empty, As it` `    ``# is only initialized to store 1` `    ``# and 2, If there are no 1 and 2` `    ``# are present in X[] values` `    ``# list will have zero length` `    ``if` `len``(values) ``=``=` `0``:` `        ``# This will execute if` `        ``# X[] doesn't contain 1 or 2` `        ``print``(N)` `        ``flag ``=` `True` `    `  `    ``# Loop for traversing over values list` `    ``for` `i ``in` `range``(``1``, ``len``(values)):` `        ``# If different adjacents are` `        ``# found like [2, 1] or [1, 2]` `        ``# in values list` `        ``if` `values[i] !``=` `values[i``-``1``]:` `            ``# Variable to hold the` `            ``# length or formally` `            ``# number of elements` `            ``# between [1, 2] or [2, 1]` `            ``x ``=` `indices[i] ``-` `indices[i``-``1``] ``-` `1` `            `  `            ``# If number of elements` `            ``# are odd, then incrementing` `            ``# ans variable by 1` `            ``if` `x ``%` `2` `=``=` `1``:` `                ``ans ``+``=` `1` `    `  `    ``# This print statement will execute` `    ``# If at least once 1 or 2` `    ``# is present in X[]` `    ``if` `flag !``=` `True``:` `        ``print``(ans)`   `# Driver Code` `if` `__name__ ``=``=` `"__main__"``:` `  ``# Inputs` `  ``N ``=` `9` `  ``X ``=` `[``1``, ``3``, ``2``, ``4``, ``5``, ``3``, ``7``, ``8``, ``1``]`   `  ``# Function call` `  ``unchanged_elements(N, X)`

## C#

 `// C# code to implement the approach` `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `GFG {`   `  ``// Method for printing unchanged elements` `  ``static` `void` `UnchangedElements(``int` `N, ``int``[] X)` `  ``{`   `    ``// List for storing indices of 1 and 2 So the we can` `    ``// calculate number of elements between them` `    ``List<``int``> indices = ``new` `List<``int``>();`   `    ``// List for storing 1 and 2, So that we can know` `    ``// different 1 and 2 are adjacents like {1, 1}, {2,` `    ``// 2} are not different adjacents but {1, 2}, {2, 1}` `    ``// are different adjacents` `    ``List<``int``> values = ``new` `List<``int``>();`   `    ``// Loop for traversing over X[] and initialize the` `    ``// both Lists` `    ``for` `(``int` `i = 0; i < N; i++) {`   `      ``// Condition when 1 and 2 found at any index` `      ``if` `(X[i] == 1 || X[i] == 2) {`   `        ``// Adding indices and values to Lists` `        ``values.Add(X[i]);` `        ``indices.Add(i);` `      ``}` `    ``}`   `    ``// ans variable to hold number of unchanged elements` `    ``long` `ans = 0;`   `    ``// Boolean flag is initialized as false` `    ``bool` `flag = ``false``;`   `    ``// Condition, When no 1 and 2 are present in X[] So` `    ``// that values List will by empty, As it is only` `    ``// initialized to store 1 and 2, If there are no 1` `    ``// and 2 are present in X[] values List will have` `    ``// zero size` `    ``if` `(values.Count == 0) {`   `      ``// This will execute if X[] doesn't contains 1` `      ``// or 2` `      ``Console.WriteLine(N);` `      ``flag = ``true``;` `    ``}`   `    ``// Loop for traversing over Lists` `    ``for` `(``int` `i = 1; i < values.Count; i++) {`   `      ``// If different adjacents are found like {2, 1}` `      ``// or {1, 2} in values List` `      ``if` `(values[i] != values[i - 1]) {`   `        ``// Variable to hold the length or formally` `        ``// number of elements between {1, 2} or {2,` `        ``// 1}` `        ``long` `x = indices[i] - indices[i - 1];` `        ``x -= 1;`   `        ``// if number of elements are odd, then` `        ``// incrementing ans variable by 1` `        ``if` `((x & 1) == 1) {` `          ``ans++;` `        ``}` `      ``}` `    ``}`   `    ``// This Print line will execute If at least once 1` `    ``// or 2 is present in X[]` `    ``if` `(flag != ``true``)` `      ``Console.WriteLine(ans);` `  ``}`   `  ``static` `public` `void` `Main()` `  ``{`   `    ``// Code` `    ``// Inputs` `    ``int` `N = 9;` `    ``int``[] X = { 1, 3, 2, 4, 5, 3, 7, 8, 1 };`   `    ``// Function call` `    ``UnchangedElements(N, X);` `  ``}` `}`   `// This code is contributed by sankar.`

## Javascript

 `// JavaScript code to implement the approach`   `// Method for printing unchanged elements` `function` `UnchangedElements(N, X) {``// Arrays for storing indices` `// of 1 and 2 So that we can` `// calculate number of elements` `// between them` `let indices = [];`   `// Array for storing 1 and 2,` `// So that we can know different 1` `// and 2 are adjacents like [1, 1],` `// [2, 2] are not different` `// adjacents but [1, 2], [2, 1]` `// are different adjacents` `let values = [];`   `// Loop for traversing over X[] and` `// initialize both the arrays` `for` `(let i = 0; i < N; i++) {`   `    ``// Condition when 1 and 2` `    ``// found at any index` `    ``if` `(X[i] == 1 || X[i] == 2) {`   `        ``// Adding indices and` `        ``// values to the arrays` `        ``values.push(X[i]);` `        ``indices.push(i);` `    ``}` `}`   `// Variable to hold number of` `// unchanged elements` `let ans = 0;`   `// Boolean flag is initialized` `// as false` `let flag = ``false``;`   `// Condition, When no 1 and 2 are` `// present in X[] So that values` `// array will be empty, As it` `// is only initialized to store 1` `// and 2, If there are no 1 and 2` `// are present in X[] values` `// array will have zero size` `if` `(values.length == 0) {`   `    ``// This will execute if` `    ``// X[] doesn't contains 1 or 2` `    ``console.log(N);` `    ``flag = ``true``;` `}`   `// Loop for traversing` `// over values array` `for` `(let i = 1; i < values.length; i++) {`   `    ``// If different adjacents are` `    ``// found like [2, 1] or [1, 2]` `    ``// in values array` `    ``if` `(values[i] != values[i - 1]) {`   `        ``// Variable to hold the` `        ``// length or formally` `        ``// number of elements` `        ``// between [1, 2] or [2, 1]` `        ``let x = indices[i] - indices[i - 1];` `        ``x -= 1;`   `        ``// if number of elements` `        ``// are odd, then incrementing` `        ``// ans variable by 1` `        ``if` `(x & 1) {` `            ``ans++;` `        ``}` `    ``}` `}`   `// This print statement will execute` `// If at least once 1 or 2` `// is present in X[]` `if` `(flag != ``true``)` `    ``console.log(ans);` `}`   `// Inputs` `let N = 9;` `let X = [1, 3, 2, 4, 5, 3, 7, 8, 1];`   `// Function call` `UnchangedElements(N, X);`

Output

`2`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up