Duplicate Zeros - Array - Easy - LeetCode
💻 coding

Duplicate Zeros - Array - Easy - LeetCode

1 min read 280 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to duplicate each occurrence of zero in a fixed-length integer array, shifting elements to the right.
  • 2The function modifies the input array in place and does not return any value.
  • 3The time complexity of the solution is O(N^2) while the space complexity is O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to duplicate each occurrence of zero in a fixed-length integer array, shifting elements to the right."

Duplicate Zeros - Array - Easy - LeetCode

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

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.Array
{
 public class DuplicateZerosSoln
 {
 public void DuplicateZeros(ref int[] arr)
 {
 for (int i = 0; i < arr.Length; i++)
 {
 if (arr[i] == 0)
 {
 if(i+1 != arr.Length)
 {
 for (int j = arr.Length-1; j > i; j--)
 {
 arr[j] = arr[j-1];
 } 
 }
 i++;
 }
 }
 }
 }
}

Time Complexity: O(N^2)

Space Complexity: O(1)

Unit Tests:

using LeetCode.AskGif.Easy.Array;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodingUnitTest.Easy.Array
{
 [TestClass]
 public class DuplicateZerosSolnTests
 {
 [TestMethod]
 public void DuplicateZerosSoln_First()
 {
 var arr = new int[] { 1, 0, 2, 3, 0, 4, 5, 0 }; 
 var expected = new int[] { 1, 0, 0, 2, 3, 0, 0, 4 };

 new DuplicateZerosSoln().DuplicateZeros(ref arr);
 AreEqual(expected, arr);
 }

 [TestMethod]
 public void DuplicateZerosSoln_Second()
 {
 var arr = new int[] { 1, 2, 3 };
 var expected = new int[] { 1, 2, 3 };

 new DuplicateZerosSoln().DuplicateZeros(ref arr);
 AreEqual(expected, arr);
 }

 private void AreEqual(int[] res, int[] output)
 {
 Assert.AreEqual(res.Length, output.Length);
 for (int i = 0; i < res.Length; i++)
 {
 Assert.AreEqual(res[i], output[i]);
 }
 }
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 19 June 2020 · 1 min read · 280 words

Part of AskGif Blog · coding

You might also like