Open In App

Reverse an Array without changing position of zeroes

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] and N, which is the size of this array, the task is to reverse this array without changing the position of zeroes in this array.

Examples:

Input: arr[] = {0, 3, 0, 6, 0, 8}, N = 6
Output: [0, 8, 0, 6, 0, 3]
Explanation: The position of the zeroes is not disturbed.

Input: arr[] = {2, 0, 5, 0, 7, 0, 3}, N = 6
Output: [3, 0, 7, 0, 5, 0, 2]

Approach: To solve the problem follow the below idea:

The approach is to traverse the array from both ends and swap the non-zero elements until the middle is reached. The position of zeroes remains unchanged during this process. The code uses a while loop to skip the zeroes and decrement the index from the end. Once a non-zero element is found, it is swapped with the non-zero element from the other end. The swapping continues until the middle is reached.

Steps that were to follow the above approach:

  • Let arr be an array of integers of size n.
  • Initialize two pointers left and right to the beginning and end of the array, respectively.
  • While the left is less than the right, repeat the following steps:
    • If arr[left] and arr[right] are both non-zero:
      • Swap arr[left] and arr[right].
      • Increment left and decrement right.
    • If arr[left] is zero, increment left.
    • If arr[right] is zero, decrement right.
  • The array arr is now reversed without changing the position of zeroes.

Below is the code to implement the above steps:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Print function
void printReverse(int* arr, int n)
{
 
    // Print the original array
    cout << "Original array: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
 
    // Reverse the array without changing
    // the position of zeroes
 
    // Initialize the index to
    // the last element
    int j = n - 1;
    for (int i = 0; i < j; i++) {
 
        // If current element is zero
        // skip to the next element
        if (arr[i] == 0) {
            continue;
        }
 
        // If current element is
        // zero from the end
        while (j > i && arr[j] == 0) {
 
            // Decrement the index to the
            // previous element
            j--;
        }
 
        // Swap the elements
        swap(arr[i], arr[j]);
 
        // Decrement the index to the
        // previous element
        j--;
    }
 
    // Print the reversed array
    cout << "Reversed array: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}
 
// Drivers code
int main()
{
 
    // input array
    int arr[] = { 2, 0, 5, 0, 7, 0, 3 };
 
    // Calculate size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printReverse(arr, N);
 
    return 0;
}


Java




import java.util.Arrays;
 
public class ReverseArrayWithoutZeros {
 
  // Print function
  public static void printReverse(int[] arr) {
 
    // Print the original array
    System.out.print("Original array: ");
    System.out.println(Arrays.toString(arr));
 
    // Reverse the array without changing
    // the position of zeroes
 
    // Initialize the index to
    // the last element
    int j = arr.length - 1;
    for (int i = 0; i < j; i++) {
 
      // If current element is zero
      // skip to the next element
      if (arr[i] == 0) {
        continue;
      }
 
      // If current element is
      // zero from the end
      while (j > i && arr[j] == 0) {
 
        // Decrement the index to the
        // previous element
        j--;
      }
 
      // Swap the elements
      int temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
 
      // Decrement the index to the
      // previous element
      j--;
    }
 
    // Print the reversed array
    System.out.print("Reversed array: ");
    System.out.println(Arrays.toString(arr));
  }
 
  // Drivers code
  public static void main(String[] args) {
 
    // input array
    int[] arr = { 2, 0, 5, 0, 7, 0, 3 };
 
    // Function call
    printReverse(arr);
  }
}


Python3




# Python code
 
# Print function
def printReverse(arr, n):
    # Print the original array
    print("Original array:", end=" ")
    for i in range(n):
        print(arr[i], end=" ")
    print()
 
    # Reverse the array without changing
    # the position of zeroes
 
    # Initialize the index to the last element
    j = n - 1
    i = 0
    while i < j:
        # If current element is zero
        # skip to the next element
        if arr[i] == 0:
            i += 1
            continue
 
        # If current element is
        # zero from the end
        while j > i and arr[j] == 0:
            # Decrement the index to the
            # previous element
            j -= 1
 
        # Swap the elements
        arr[i], arr[j] = arr[j], arr[i]
 
        # Decrement the index to the
        # previous element
        j -= 1
        i += 1
 
    # Print the reversed array
    print("Reversed array:", end=" ")
    for i in range(n):
        print(arr[i], end=" ")
    print()
 
# Driver code
arr = [2, 0, 5, 0, 7, 0, 3]
N = len(arr)
 
# Function call
printReverse(arr, N)
 
# This code is contributed by Vaibhav nandan


C#




// C# code implementation:
 
using System;
 
public class GFG {
 
    // Print function
    static void printReverse(int[] arr)
    {
        // Print the original array
        Console.Write("Original array: ");
        Console.WriteLine(string.Join(", ", arr));
 
        // Reverse the array without changing
        // the position of zeroes
 
        // Initialize the index to
        // the last element
        int j = arr.Length - 1;
        for (int i = 0; i < j; i++) {
 
            // If current element is zero
            // skip to the next element
            if (arr[i] == 0) {
                continue;
            }
 
            // If current element is
            // zero from the end
            while (j > i && arr[j] == 0) {
 
                // Decrement the index to the
                // previous element
                j--;
            }
 
            // Swap the elements
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
 
            // Decrement the index to the
            // previous element
            j--;
        }
 
        // Print the reversed array
        Console.Write("Reversed array: ");
        Console.WriteLine(string.Join(", ", arr));
    }
 
    static public void Main()
    {
 
        // Code
        int[] arr = { 2, 0, 5, 0, 7, 0, 3 };
 
        // Function call
        printReverse(arr);
    }
}
 
// This code is contributed by sankar.


Javascript




function printReverse(arr, n) {
  // Print the original array
  console.log("Original array: " + arr.join(" "));
 
  // Reverse the array without changing the position of zeroes
  let j = n - 1;
  for (let i = 0; i < j; i++) {
    // If current element is zero, skip to the next element
    if (arr[i] === 0) {
      continue;
    }
 
    // If current element is zero from the end
    while (j > i && arr[j] === 0) {
      // Decrement the index to the previous element
      j--;
    }
 
    // Swap the elements
    [arr[i], arr[j]] = [arr[j], arr[i]];
 
    // Decrement the index to the previous element
    j--;
  }
 
  // Print the reversed array
  console.log("Reversed array: " + arr.join(" "));
}
 
// Driver code
const arr = [2, 0, 5, 0, 7, 0, 3];
const N = arr.length;
printReverse(arr, N);
 
// This code is contributed by Tushar Rokade


Output

Original array: 2 0 5 0 7 0 3 
Reversed array: 3 0 7 0 5 0 2 

Time complexity: O(N)
Auxiliary Space: O(1)



Last Updated : 10 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads