FastPrepDuplicate Zeros

Duplicate Zeros

Microsoft logoMicrosoft● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given a fixed-length integer array arr, duplicate each occurrence of 0. Shift the remaining values to the right and discard any values that move beyond the original array length.

Modify the array in place. For the practice runner, return the same array after it has been mutated.

Function

duplicateZeros(arr: int[]) → int[]

Examples

Example 1

arr = [1,0,2,3,0,4,5,0]return = [1,0,0,2,3,0,0,4]

Each zero is copied once. Values shifted beyond the eighth position are discarded.

Example 2

arr = [1,2,3]return = [1,2,3]

There are no zeros to duplicate, so the array is unchanged.

Constraints

  • 1 <= arr.length <= 100000
  • 0 <= arr[i] <= 10^9

More Microsoft problems

See Microsoft hiring insights
public int[] duplicateZeros(int[] arr) {
  // Write your code here.
}
arr[1,0,2,3,0,4,5,0]
expected[1,0,0,2,3,0,0,4]
Checking account…