# LeetCode: Move Zeroes Solution

Go for an optimal solution in the first go could lead to frustration

## Approach: Nested Loops

Exhausively check all the index pairs and swap

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var moveZeroes = function (nums) {2  const N = nums.length3
4  for (let i = 0; i < N - 1; i++) {5    for (let j = i + 1; j < N; j++) {6      if (nums[i] === 0) {7        ;[nums[i], nums[j]] = [nums[j], nums[i]]8      }9    }10  }11}```

## Approach: Isolated Loops

One loop is to fill all non-zero numbers to the first part

One loop is to fill the rest zeroes to the rest part

## Implementation

```1var moveZeroes = function (nums) {2  const n = nums.length3  let i = 04
5  for (const num of nums) {6    if (num !== 0) nums[i++] = num7  }8
9  for (; i < n; i++) {10    nums[i] = 011  }12}```

leetcode

array

two pointers

## Next Post

LeetCode: Implement Strstr

Feb 5, 2021

## Previous Post

LeetCode: Reverse String

Feb 5, 2021

Built-in string method

Search Posts