Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Make all array elements equal by replacing adjacent pairs by their sum
Next article icon

Modify Array by modifying adjacent equal elements

Last Updated : 14 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N of positive integers. The task is to rearrange the array after applying the conditions given below: 

  • If arr[i] and arr[i+1] are equal then multiply the ith (current) element with 2 and set the (i +1)th element to 0. 
  • After applying all the conditions move all zeros at the end of the array.

Examples:

Input: N = 6,  arr[] = [1, 2, 2, 1, 1, 0]
Output: [1, 4, 2, 0, 0, 0]
Explanation: At i = 0: arr[0] and arr[1] are not the same, so we do nothing.
At i = 1: arr[1] and arr[2] are the same, so we multiply arr[1] with 2 and change its next element to 0.
array = [1, 4, 0, 1, 1, 0]
 At i = 2: arr[2] and arr[3] are not the same, so we do nothing.
At i = 3: arr[3] and arr[4] are the same, so we multiply arr[3] with 2 and change its next element to 
arr[] = [1, 4, 0, 2, 0, 0]
At i = 4: arr[4] and arr[5] are the same, so we multiply arr[4] with 2 and change its next element to 0.
arr[] = [1, 4, 0, 2, 0, 0]
After applying the above 2 conditions, shift all the 0's to the right side of the array.
arr[]= [1, 4, 2, 0, 0, 0]

Input: N =2, arr[] = [0, 1]
Output: [1, 0]
Explanation: At i = 0: arr[0] and arr[1] are not same, so we do nothing.
No conditions can be applied further, so we shift all 0's to right.
arr[] = [1, 0]

Approach: Linear Iteration

The basic idea is to linearly iterate the array and check whether the conditions are satisfied or not and perform operations according to the conditions.

Illustration:

Consider an array arr[] = {1, 2, 2, 1, 1, 0};

At i = 0: 
arr[0] and arr[1] are not the same, so we do nothing.

At i = 1:
arr[1] and arr[2] are the same, so we multiply arr[1] with 2 and change its next element to 0.
arr[] = [1, 4, 0, 1, 1, 0]

At i = 2:
arr[2] and arr[3] are not the same, so we do nothing.

At i = 3:
arr[3] and arr[4] are the same, so we multiply arr[3] with 2 and change its next element to 0.
arr[]= [1, 4, 0, 2, 0, 0]

At i = 4:
arr[4] and arr[5] are the same, so we multiply arr[4] with 2 and change it's next element to 0.
arr[] = [1, 4, 0, 2, 0, 0]

After applying the above 2 conditions, shift all the 0's to right side of the array.
arr[] = [1, 4, 2, 0, 0, 0]

Follow the steps below to implement the above idea:

  • Traverse through the given array from i = 0 to N-2.
  • If the ith element is equal to the next element then,
    • Multiply the current element with 2 arr[i]*2.
    • Set next element arr[i]+1 with 0.
  • Now right shift all the 0's.
    • Create a counter variable count to count the number of non-zero elements of the array.
    • If arr[i] is not zero then just update the array with counter variable arr[count++] = arr[i].
  • set all zeroes at the end of the array.

Below is the implementation of the above approach.

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to shift all zeros to right side of array void rightShift(int arr[], int n) {     int count = 0;      for (int i = 0; i < n; i++) {         if (arr[i] != 0) {             arr[count++] = arr[i];         }     }      while (count < n) {         arr[count++] = 0;     } }  // Function to apply the given conditions void applyConditions(int arr[], int n) {     for (int i = 0; i < n - 1; i++) {          // Condition 1         if (arr[i] == arr[i + 1]) {             arr[i] = arr[i] * 2;             arr[i + 1] = 0;         }          // Condition 2         else {             continue;         }     }      // Function Call     rightShift(arr, n); }  // Driver Code int main() {     int arr[] = { 1, 2, 2, 1, 1, 0 };     int N = sizeof(arr) / sizeof(arr[0]);      // Function Call     applyConditions(arr, N);      for (int i = 0; i < N; i++) {         cout << arr[i] << " ";     }      return 0; }  // This code is contributed by Tapesh(tapeshdua420) 
Java
// Java code to implement the approach  import java.io.*;  class GFG {      // Function to apply the given conditions     static void applyConditions(int[] arr, int n)     {         for (int i = 0; i < n - 1; i++) {              // Condition 1             if (arr[i] == arr[i + 1]) {                 arr[i] = arr[i] * 2;                 arr[i + 1] = 0;             }              // Condition 2             else {                 continue;             }         }          // Function Call         rightShift(arr, n);     }      // Function to shift all zeros to right side of array     static void rightShift(int[] arr, int n)     {         int count = 0;          for (int i = 0; i < n; i++) {             if (arr[i] != 0) {                 arr[count++] = arr[i];             }         }          while (count < n) {             arr[count++] = 0;         }     }      // Driver Code     public static void main(String[] args)     {         int[] arr = { 1, 2, 2, 1, 1, 0 };         int N = arr.length;          // Function Call         applyConditions(arr, N);          for (int i = 0; i < N; i++) {             System.out.print(arr[i] + " ");         }     } } 
Python3
# Python code to implement the approach  # Function to shift all zeros to right side of array   def rightShift(arr, n):      count = 0      for i in range(n):         if (arr[i] != 0):             arr[count] = arr[i]             count += 1      while (count < n):         arr[count] = 0         count += 1  # Function to apply the given conditions   def applyConditions(arr, n):      for i in range(n - 1):          # Condition 1         if (arr[i] == arr[i + 1]):             arr[i] = arr[i] * 2             arr[i + 1] = 0          # Condition 2         else:             continue      # Function Call     rightShift(arr, n)   # Driver Code if __name__ == '__main__':      arr = [1, 2, 2, 1, 1, 0]     N = len(arr)      # Function Call     applyConditions(arr, N)      for i in range(N):         print(arr[i], end=" ")  # This code is contributed by Tapesh(tapeshdua420) 
C#
// C# code to implement the approach  using System;  public class GFG {      // Function to apply the given conditions     static void applyConditions(int[] arr, int n)     {         for (int i = 0; i < n - 1; i++) {              // Condition 1             if (arr[i] == arr[i + 1]) {                 arr[i] = arr[i] * 2;                 arr[i + 1] = 0;             }              // Condition 2             else {                 continue;             }         }          // Function Call         rightShift(arr, n);     }      // Function to shift all zeros to right side of array     static void rightShift(int[] arr, int n)     {         int count = 0;          for (int i = 0; i < n; i++) {             if (arr[i] != 0) {                 arr[count++] = arr[i];             }         }          while (count < n) {             arr[count++] = 0;         }     }      static public void Main()     {          // Code         int[] arr = { 1, 2, 2, 1, 1, 0 };         int N = arr.Length;          // Function Call         applyConditions(arr, N);          for (int i = 0; i < N; i++) {             Console.Write(arr[i] + " ");         }     } }  // This code is contributed by lokeshmvs21. 
JavaScript
// JS code to implement the approach       // Function to apply the given conditions function applyConditions(arr, n)     {         for (let i = 0; i < n - 1; i++) {              // Condition 1             if (arr[i] == arr[i + 1]) {                 arr[i] = arr[i] * 2;                 arr[i + 1] = 0;             }              // Condition 2             else {                 continue;             }         }          // Function Call         rightShift(arr, n);     }      // Function to shift all zeros to right side of array function rightShift(arr, n)     {         let count = 0;          for (let i = 0; i < n; i++) {             if (arr[i] != 0) {                 arr[count++] = arr[i];             }         }          while (count < n) {             arr[count++] = 0;         }     }           let arr = [ 1, 2, 2, 1, 1, 0 ];         let N = arr.length;          // Function Call         applyConditions(arr, N);          for (let i = 0; i < N; i++) {             console.log(arr[i] + " ");         }  // This code is contributed by ksam24000. 

Output
1 4 2 0 0 0 

Time Complexity: O(N), because we are iterating the array two times.
Auxiliary Space: O(1)

Related Articles:

  • Introduction to Arrays - Data Structures and Algorithms Tutorials

Next Article
Make all array elements equal by replacing adjacent pairs by their sum

U

user_7gr9iodclfx
Improve
Article Tags :
  • Technical Scripter
  • DSA
  • Arrays
  • Technical Scripter 2022
  • array-rearrange
Practice Tags :
  • Arrays

Similar Reads

  • Equalize an array using array elements only
    Given an array of integers, the task is to count minimum number of operations to equalize the array (make all array elements same). And return -1 if it is not possible to equalize. To equalize an array, we need to move values from higher numbers to smaller numbers. Number of operations is equal to n
    6 min read
  • Make all Array elements equal by replacing it with adjacent elements
    Given an array A[] of size N, the task is to find the minimum number of moves required to make array elements equal where you can make adjacent elements equal in one move. Examples: Input: A = {1, 6, 5, 1, 7, 1}, N = 6Output: 3Explanation: Replace 6 with 1, 5 with 1, and then at last replace 7 with
    5 min read
  • Make all array elements equal by replacing adjacent pairs by their sum
    Given an array arr[] consisting of N integers, the task is to replace a minimum number of pairs of adjacent elements by their sum to make all array elements equal. Print the minimum number of such operations required. Examples: Input: arr[] = {1, 2, 3}Output: 1Explanation: Replace arr[0] and arr[1]
    8 min read
  • Modify matrix by increments such that no pair of adjacent elements are equal
    Given a square matrix mat[][] of size N * N, the task is to print the matrix after incrementing matrix elements such that no two adjacent elements of the matrix are equal. Examples: Input: mat[][] = { { 1, 2, 2 }, { 3, 2, 2 }, { 2, 2, 2 } } Output: { { 2, 3, 2 }, { 3, 2, 3 }, { 2, 3, 2 } } Explanati
    12 min read
  • Generate an array from given pairs of adjacent elements
    Given a 2D array arr[][] consisting of N pairs of integers such that the two elements in each row indicates that they are adjacent elements in the original array. The task is to construct an array with given pairs of adjacent elements of arr[]. Examples Input: arr[] = {{5, 1 }, {3, 4 }, {3, 5}} Outp
    8 min read
  • Distinct adjacent elements in an array
    Given an array, find whether it is possible to obtain an array having distinct neighbouring elements by swapping two neighbouring array elements. Examples: Input : 1 1 2 Output : YES swap 1 (second last element) and 2 (last element), to obtain 1 2 1, which has distinct neighbouring elements . Input
    7 min read
  • Modify array to maximize sum of adjacent differences
    Given an array, we need to modify the values of this array in such a way that the sum of absolute differences between two consecutive elements is maximized. If the value of an array element is X, then we can change it to either 1 or X. Examples : Input : arr[] = [3, 2, 1, 4, 5] Output : 8 We can mod
    9 min read
  • Minimizing Moves to Equalize Array Elements
    Given an array arr[] of N integers, For each move, you can select any m (1 <= m <= n) elements from the array and transfer one integer unit from each selected element to one of its adjacent elements at the same time, the task is to find the minimum number of moves needed to make all the intege
    7 min read
  • Make all array elements equal with minimum cost
    Given an array of size n, the task is to make the value of all elements equal with minimum cost. The cost of changing a value from x to y is abs(x - y). Examples : Input: arr[] = [1, 100, 101]Output: 100Explanation: We can change all its values to 100 with minimum cost,|1 - 100| + |100 - 100| + |101
    15 min read
  • Modify array by removing (arr[i] + arr[i + 1])th element exactly K times
    Given an array arr[] consisting of first N natural numbers, where arr[i] = i ( 1-based indexing ) and a positive integer K, the task is to print the array arr[] obtained after removing every (arr[i] + arr[i + 1])th element from the array in every ith operation exactly K times. Examples: Input: arr[]
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences