Double the first element and move zero to end - GeeksforGeeks

28 Jan, 2022
For a given array of n integers and assume that ‘0’ is an invalid number and all others as a valid number. Convert the array in such a way that if both current and next element is valid and both have same value then double current value and replace the next number with 0. After the modification, rearrange the array such that all 0’s shifted to the end. Examples: 
Input : arr[] = {2, 2, 0, 4, 0, 8}
Output : 4 4 8 0 0 0

Input : arr[] = {0, 2, 2, 2, 0, 6, 6, 0, 0, 8}
Output :  4 2 12 8 0 0 0 0 0 0
Source: Microsoft IDC Interview Experience | Set 150.
Approach: First modify the array as mentioned, i.e., if the next valid number is the same as the current number, double its value and replace the next number with 0. Algorithm for Modification:  
1. if n == 1
2.     return
3. for i = 0 to n-2
4.     if (arr[i] != 0) && (arr[i] == arr[i+1])
5.         arr[i] = 2 * arr[i]
6.       arr[i+1] = 0
7.       i++
After modifying the array, Move all zeroes to the end of the array.
C++
Java
Python3
C#
Javascript
// C++ implementation to rearrange the array// elements after modification#include <bits/stdc++.h> using namespace std; // function which pushes all zeros to end of// an array.void pushZerosToEnd(int arr[], int n){    // Count of non-zero elements    int count = 0;     // Traverse the array. If element encountered    // is non-zero, then replace the element at    // index 'count' with this element    for (int i = 0; i < n; i++)        if (arr[i] != 0)             // here count is incremented            arr[count++] = arr[i];     // Now all non-zero elements have been shifted    // to front and 'count' is set as index of    // first 0. Make all elements 0 from count    // to end.    while (count < n)        arr[count++] = 0;} // function to rearrange the array elements// after modificationvoid modifyAndRearrangeArr(int arr[], int n){    // if 'arr[]' contains a single element    // only    if (n == 1)        return;     // traverse the array    for (int i = 0; i < n - 1; i++) {         // if true, perform the required modification        if ((arr[i] != 0) && (arr[i] == arr[i + 1])) {             // double current index value            arr[i] = 2 * arr[i];             // put 0 in the next index            arr[i + 1] = 0;             // increment by 1 so as to move two            // indexes ahead during loop iteration            i++;        }    }     // push all the zeros at the end of 'arr[]'    pushZerosToEnd(arr, n);} // function to print the array elementsvoid printArray(int arr[], int n){    for (int i = 0; i < n; i++)        cout << arr[i] << " ";} // Driver program to test aboveint main(){    int arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 };    int n = sizeof(arr) / sizeof(arr[0]);     cout << "Original array: ";    printArray(arr, n);     modifyAndRearrangeArr(arr, n);     cout << "\nModified array: ";    printArray(arr, n);     return 0;}
// Java implementation to rearrange the// array elements after modificationclass GFG {     // function which pushes all    // zeros to end of an array.    static void pushZerosToEnd(int arr[], int n)    {        // Count of non-zero elements        int count = 0;         // Traverse the array. If element        // encountered is non-zero, then        // replace the element at index        // 'count' with this element        for (int i = 0; i < n; i++)            if (arr[i] != 0)                 // here count is incremented                arr[count++] = arr[i];         // Now all non-zero elements        // have been shifted to front and        // 'count' is set as index of first 0.        // Make all elements 0 from count to end.        while (count < n)            arr[count++] = 0;    }     // function to rearrange the array    //  elements after modification    static void modifyAndRearrangeArr(int arr[], int n)    {        // if 'arr[]' contains a single element        // only        if (n == 1)            return;         // traverse the array        for (int i = 0; i < n - 1; i++) {             // if true, perform the required modification            if ((arr[i] != 0) && (arr[i] == arr[i + 1]))            {                 // double current index value                arr[i] = 2 * arr[i];                 // put 0 in the next index                arr[i + 1] = 0;                 // increment by 1 so as to move two                // indexes ahead during loop iteration                i++;            }        }         // push all the zeros at        // the end of 'arr[]'        pushZerosToEnd(arr, n);    }     // function to print the array elements    static void printArray(int arr[], int n)    {        for (int i = 0; i < n; i++)            System.out.print(arr[i] + " ");        System.out.println();    }     // Driver program to test above    public static void main(String[] args)    {        int arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 };        int n = arr.length;         System.out.print("Original array: ");        printArray(arr, n);         modifyAndRearrangeArr(arr, n);         System.out.print("Modified array: ");        printArray(arr, n);    }} // This code is contributed // by prerna saini
# Python3 implementation to rearrange# the array elements after modification # function which pushes all zeros# to end of an array.def pushZerosToEnd(arr, n):     # Count of non-zero elements    count = 0     # Traverse the array. If element    # encountered is non-zero, then    # replace the element at index    # 'count' with this element    for i in range(0, n):        if arr[i] != 0:             # here count is incremented            arr[count] = arr[i]            count+=1     # Now all non-zero elements have been    # shifted to front and 'count' is set    # as index of first 0. Make all    # elements 0 from count to end.    while (count < n):        arr[count] = 0        count+=1  # function to rearrange the array# elements after modificationdef modifyAndRearrangeArr(ar, n):     # if 'arr[]' contains a single    # element only    if n == 1:        return     # traverse the array    for i in range(0, n - 1):         # if true, perform the required modification        if (arr[i] != 0) and (arr[i] == arr[i + 1]):             # double current index value            arr[i] = 2 * arr[i]             # put 0 in the next index            arr[i + 1] = 0             # increment by 1 so as to move two            # indexes ahead during loop iteration            i+=1           # push all the zeros at the end of 'arr[]'    pushZerosToEnd(arr, n)  # function to print the array elementsdef printArray(arr, n):     for i in range(0, n):        print(arr[i],end=" ")  # Driver program to test abovearr = [ 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 ]n = len(arr) print("Original array:",end=" ")printArray(arr, n) modifyAndRearrangeArr(arr, n) print("\nModified array:",end=" ")printArray(arr, n) # This code is contributed by Smitha Dinesh Semwal
// C# implementation to rearrange the// array elements after modificationusing System; class GFG {     // function which pushes all    // zeros to end of an array.    static void pushZerosToEnd(int[] arr, int n)    {        // Count of non-zero elements        int count = 0;         // Traverse the array. If element        // encountered is non-zero, then        // replace the element at index        // 'count' with this element        for (int i = 0; i < n; i++)            if (arr[i] != 0)                 // here count is incremented                arr[count++] = arr[i];         // Now all non-zero elements        // have been shifted to front and        // 'count' is set as index of first 0.        // Make all elements 0 from count to end.        while (count < n)            arr[count++] = 0;    }     // function to rearrange the array    // elements after modification    static void modifyAndRearrangeArr(int[] arr, int n)    {        // if 'arr[]' contains a single element        // only        if (n == 1)            return;         // traverse the array        for (int i = 0; i < n - 1; i++) {             // if true, perform the required modification            if ((arr[i] != 0) && (arr[i] == arr[i + 1])) {                 // double current index value                arr[i] = 2 * arr[i];                 // put 0 in the next index                arr[i + 1] = 0;                 // increment by 1 so as to move two                // indexes ahead during loop iteration                i++;            }        }         // push all the zeros at        // the end of 'arr[]'        pushZerosToEnd(arr, n);    }     // function to print the array elements    static void printArray(int[] arr, int n)    {        for (int i = 0; i < n; i++)            Console.Write(arr[i] + " ");        Console.WriteLine();    }     // Driver program to test above    public static void Main()    {        int[] arr = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 };        int n = arr.Length;         Console.Write("Original array: ");        printArray(arr, n);         modifyAndRearrangeArr(arr, n);         Console.Write("Modified array: ");        printArray(arr, n);    }} // This code is contributed by Sam007
<script>      // JavaScript implementation to rearrange the array      // elements after modification       // function which pushes all zeros to end of      // an array.      function pushZerosToEnd(arr, n)      {        // Count of non-zero elements        var count = 0;         // Traverse the array. If element encountered        // is non-zero, then replace the element at        // index 'count' with this element        for (var i = 0; i < n; i++)          if (arr[i] != 0)            // here count is incremented            arr[count++] = arr[i];         // Now all non-zero elements have been shifted        // to front and 'count' is set as index of        // first 0. Make all elements 0 from count        // to end.        while (count < n) arr[count++] = 0;      }       // function to rearrange the array elements      // after modification      function modifyAndRearrangeArr(arr, n)      {               // if 'arr[]' contains a single element        // only        if (n == 1) return;         // traverse the array        for (var i = 0; i < n - 1; i++)        {                   // if true, perform the required modification          if (arr[i] != 0 && arr[i] == arr[i + 1]) {            // double current index value            arr[i] = 2 * arr[i];             // put 0 in the next index            arr[i + 1] = 0;             // increment by 1 so as to move two            // indexes ahead during loop iteration            i++;          }        }         // push all the zeros at the end of 'arr[]'        pushZerosToEnd(arr, n);      }       // function to print the array elements      function printArray(arr, n)      {        for (var i = 0; i < n; i++) document.write(arr[i] + " ");      }       // Driver program to test above      var arr = [0, 2, 2, 2, 0, 6, 6, 0, 0, 8];      var n = arr.length;       document.write("Original array: ");      printArray(arr, n);       modifyAndRearrangeArr(arr, n);      document.write("<br>");      document.write("Modified array: ");      printArray(arr, n);             // This code is contributed by rdtank.    </script>
Output: 
Original array: 0 2 2 2 0 6 6 0 0 8
Modified array: 4 2 12 8 0 0 0 0 0 0
Time Complexity: O(n). 
Approach with efficient zero shiftings:
Although the above solution is efficient, we can further optimise it in shifting zero algorithms by reducing the number of operations.
In the above shifting algorithms, we scan some elements twice when we set the count index to last index element to zero.
Efficient Zero Shifting Algorithms:
int lastSeenPositiveIndex = 0;
for( index = 0; index < n; index++)
{
    if(array[index] != 0)
    {
        swap(array[index], array[lastSeenPositiveIndex]);
        lastSeenPositiveIndex++;
    }
}
C++
Java
Python3
C#
Javascript
// Utility Function For Swapping Two Element Of An Arrayvoid swap(int& a, int& b) { a = b + a - (b = a); } // shift all zero to left side of an arrayvoid shiftAllZeroToLeft(int array[], int n){    // Maintain last index with positive value    int lastSeenNonZero = 0;     for (index = 0; index < n; index++)    {        // If Element is non-zero        if (array[index] != 0)        {            // swap current index, with lastSeen non-zero            swap(array[index], array[lastSeenNonZero]);             // next element will be last seen non-zero            lastSeenNonZero++;        }    }} // This snippet is contributed By: Faizanur Rahman
class GFG {    // Function For Swapping Two Element Of An Array    public static void swap(int[] A, int i, int j)    {        int temp = A[i];        A[i] = A[j];        A[j] = temp;    }     // shift all zero to left side of an array    static void shiftAllZeroToLeft(int array[], int n)    {        // Maintain last index with positive value        int lastSeenNonZero = 0;         for (int index = 0; index < n; index++) {            // If Element is non-zero            if (array[index] != 0) {                // swap current index, with lastSeen                // non-zero                swap(array, array[index],                     array[lastSeenNonZero]);                 // next element will be last seen non-zero                lastSeenNonZero++;            }        }    }} // This code is contributed By sam_2200
# Maintain last index with positive valuedef shiftAllZeroToLeft(arr, n):    lastSeenNonZero = 0    for index in range(0, n):               # If Element is non-zero        if (array[index] != 0):                       # swap current index, with lastSeen            # non-zero            array[index], array[lastSeenNonZero] = array[lastSeenNonZero], array[index]                         # next element will be last seen non-zero            lastSeenNonZero++             # This code is contributed By sam_2200
using System;class GFG{       // Function For Swapping Two Element Of An Array    public static void swap(int[] A, int i, int j)    {        int temp = A[i];        A[i] = A[j];        A[j] = temp;    }     // shift all zero to left side of an array    static void shiftAllZeroToLeft(int[] array, int n)    {               // Maintain last index with positive value        int lastSeenNonZero = 0;         for (int index = 0; index < n; index++)        {                       // If Element is non-zero            if (array[index] != 0)            {                               // swap current index, with lastSeen                // non-zero                swap(array, array[index],                     array[lastSeenNonZero]);                 // next element will be last seen non-zero                lastSeenNonZero++;            }        }    }} // This code is contributed By Saurabh Jaiswal
<script>     // Function For Swapping Two Element Of An Array    function swap(A,i,j)    {        let temp = A[i];        A[i] = A[j];        A[j] = temp;    }     // shift all zero to left side of an array    function shiftAllZeroToLeft(array,n)    {        // Maintain last index with positive value        let lastSeenNonZero = 0;         for (let index = 0; index < n; index++) {            // If Element is non-zero            if (array[index] != 0) {                // swap current index, with lastSeen                // non-zero                swap(array, array[index],                    array[lastSeenNonZero]);                 // next element will be last seen non-zero                lastSeenNonZero++;            }        }    }} // This code is contributed by sravan kumar Gottumukkala </script>
sagarika3kundu
faizanurrahman
sam_2200
rdtank
sravankumar8128
guneshshanbhag
_saurabh_jaiswal
rkbhola5
array-rearrange
Microsoft
Zoho
Arrays
Zoho
Microsoft
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Linked List vs Array
Python | Using 2D arrays/lists the right way
Given an array of size n and a number k, find all elements that appear more than n/k times
Queue | Set 1 (Introduction and Array Implementation)
Subset Sum Problem | DP-25
K'th Smallest/Largest Element in Unsorted Array | Set 1
Find the Missing Number
Array of Strings in C++ (5 Different Ways to Create)
Next Greater Element