Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

Leetcode: Duplicate Zeros

Posted on June 18, 2019October 7, 2019 by braindenny

Duplicate Zeros



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • 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 #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #misc #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum baseconversion binarysearch concurrency editdistance hashmap knapsack monotone oodesign presum redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • Leetcode: Palindrome Partitioning III
  • Leetcode: Biggest Single Number
  • Leetcode: Max Consecutive Ones II
  • Leetcode: Minimum Cost to Connect Sticks
  • Leetcode: Minimum Swaps to Group All 1’s Together

Recent Comments

    Archives

    Categories

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