Move zeros to end (stable)

Move zeros to end (stable)

Medium Java Arrays 28 views
Explanation Complexity

Problem Statement

Task: move all zeros to the end while keeping the relative order of non-zero elements.

Input Format

An integer n (size of array)
Then n integers (array elements)

Output Format

Array after moving all 0s to the end
(keeping relative order of non-zero elements)

Example

7
0 1 0 3 12 0 5
1 3 12 5 0 0 0

Constraints

• n ≥ 1

• Do it in-place (no extra array)

• Preserve order of non-zero elements

Concept Explanation

All non-zero elements should stay in the same order.
All zeros should be shifted to the end.

Step-by-Step Explanation

1.Read array size n.

2.Read n elements into the array.

3.Initialize index = 0.

4.Loop through the array from 0 to n-1:

• If current element is not zero:

• Place it at arr[index].

• Increment index.

5.After the loop, from index to n-1:

• Set elements to 0.

6.Print the updated array.

Concept Explanation

All non-zero elements should stay in the same order.
All zeros should be shifted to the end.

Step-by-Step Explanation

1.Read array size n.

2.Read n elements into the array.

3.Initialize index = 0.

4.Loop through the array from 0 to n-1:

• If current element is not zero:

• Place it at arr[index].

• Increment index.

5.After the loop, from index to n-1:

• Set elements to 0.

6.Print the updated array.

Input / Output Format

Input Format
An integer n (size of array)
Then n integers (array elements)
Output Format
Array after moving all 0s to the end
(keeping relative order of non-zero elements)
Constraints
• n ≥ 1

• Do it in-place (no extra array)

• Preserve order of non-zero elements

Examples

Input:
7 0 1 0 3 12 0 5
Output:
1 3 12 5 0 0 0

Example Solution (Public)

Java
static void moveZeros(int[] a){int w=0;for(int x:a) if(x!=0) a[w++]=x;while(w<a.length) a[w++]=0;}

Official Solution Code

static void moveZeros(int[] a){int w=0;for(int x:a) if(x!=0) a[w++]=x;while(w<a.length) a[w++]=0;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.