Learner Level

Implement the moveZerosToEndCopy method that returns a copy of the array with all zero values moved to the end.

The input contains an integer array nums and its length size. Your task is to return a new array where all non-zero values keep their original order and all zero values are moved to the end.

For example, [0,1,0,3,12] becomes [1,3,12,0,0]. The relative order of 1, 3, and 12 must remain the same.

Example 1

Input
nums (int[]) = [0,1,0,3,12]
size (int) = 5
Returns (int[]) [1,3,12,0,0]

Example 2

Input
nums (int[]) = [1,2,3]
size (int) = 3
Returns (int[]) [1,2,3]

Example 3

Input
nums (int[]) = [0,0,5]
size (int) = 3
Returns (int[]) [5,0,0]

Build a new array in two steps.

First, copy every non-zero value to the result. Then count or append the required number of zeroes at the end until the result has the same length as the input.

Pseudocode:

function moveZerosToEndCopy(nums, size):
    result = empty array
    zeroCount = 0
    for each value in nums:
        if value == 0:
            zeroCount++
        else:
            add value to result
    repeat zeroCount times:
        add 0 to result
    return result
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.