Move Zeroes - Leet Code Solution

September 03, 2020

Problem Statement

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Example

``````Input: [0,1,0,3,12]
Output: [1,3,12,0,0]``````

Solution (copying to left)

We can keep a index variable which will keep a tab on all non-zero values.

On iteration, we can move each non-zero value to left side.

Code

``````public void moveZeroes_simple(int[] nums) {
int left=0;

for (int i=0; i<nums.length; i++) {
if (nums[i] != 0) {
nums[left] = nums[i];
left ++;
}
}

//copy zeroes to remaining array
for (int i=left; i<nums.length; i++) {
nums[i] = 0;
}
}``````

Complexity

Its `O(n)`

Another Solution (Swapping)

We can do a slight modification to above solution. The point where we just move non-zero value to left. We can do a swap as well.

Code

``````public void moveZeroes(int[] nums) {
int left=0;

for (int i=0; i<nums.length; i++) {
if (nums[i] != 0) {
//swap
int t = nums[i];
nums[i] = nums[left];
nums[left] = t;

left ++;
}
}
}``````

Complexity

Its `O(n)`
But, its better since we are not using another loop to copy zero.

Similar Posts

Replace all spaces in a string with %20

Problem Statement Replace all spaces in a string with ‘%20’ (three characters…

First Unique Character in a String - Leet Code Solution

Problem Statement Given a string, find the first non-repeating character in it…

Graph Topological Sorting - Build System Order Example

Graph Topological Sorting This is a well known problem in graph world…

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Rotate Array - Leet Code Solution

Problem Statement Given an array, rotate the array to the right by k steps…

Crawler Log Folder - minimum number of operations needed to go back to the main folder after the change folder operations.

Problem The Leetcode file system keeps a log each time some user performs a…

Latest Posts

Authenticating Strapi backend with Next.js and next-auth using credentials and jwt

Introduction Strapi is a backend system provides basic crud operations with…

How to create Repository using Github Rest API, Configure Visibility and Assign a Team as Readonly

Introduction I had to create many repositories in an Github organization. I…

How to Download multiple Youtube Videos using Nodejs and Show a Progress Bar

Introduction I was trying to download some youtube videos for my kids. As I have…

Python - Some useful Pytest Commands

Introduction In this post, we will explore some useful command line options for…

Python - How to apply patch to Python and Install Python via Pyenv

Introduction In this post, we will see how we can apply a patch to Python and…

How to Install packages from command line and Dockerfile with Chocolatey

Introduction We will introduce a Package Manager for Windows: . In automations…