LeetCode: Duplicate Zeros Posted on June 18, 2019July 26, 2020 by braindenny Duplicate Zeros Similar Problems: CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #twopointer, #array, #inspiring, #findduplicates Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place, do not return anything from your function. Example 1: Input: [1,0,2,3,0,4,5,0] Output: null Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] Example 2: Input: [1,2,3] Output: null Explanation: After calling your function, the input array is modified to: [1,2,3] Note: 1 <= arr.length <= 10000 0 <= arr[i] <= 9 Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. Solution: // https://code.dennyzhang.com/duplicate-zeros // Basic Ideas: two pointer // Find how many cells can be shifted // From right to next, do the move // Complexity: Time O(n), Space O(1) func duplicateZeros(arr []int) { count := 0 for _, v := range arr { if v == 0 { count++ } } i, j := len(arr)-1, len(arr)+count-1 for ; i>=0 && j>=0; i, j = i-1, j-1 { if arr[i] != 0 { if j<len(arr) { arr[j] = arr[i] } } else { if j<len(arr) { arr[j] = 0 } j-- if j<len(arr) { arr[j] = 0 } } } } Post Views: 0