Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

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. 1 <= arr.length <= 10000
  2. 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
            }
        }
    }
}
linkedin
github
slack

Post Views: 0
Posted in BasicTagged #array, #inspiring, #twopointer, findduplicates

Post navigation

LeetCode: Two City Scheduling
LeetCode: Last Stone Weight

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.