

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Duplicate Zeros in Python
Suppose we have a fixed length array of integers, we have to duplicate each occurrence of zero, shifting the remaining elements to the right side.
Note that elements beyond the length of the original array are not written.
So suppose the array is like [1,0,2,3,0,4,5,0], then after modification it will be [1,0,0,2,3,0,0,4]
To solve this, we will follow these steps −
- copy arr into another array arr2, set i and j as 0
- while i < size of arr −
- if arr2[i] is zero, then
- arr[i] := 0
- increase i by 1
- if i < size of arr, then arr[i] := 0
- else arr[i] := arr2[j]
- increase i and j by 1
- if arr2[i] is zero, then
Example
Let us see the following implementation to get better understanding −
class Solution(object): def duplicateZeros(self, arr): arr2 = [i for i in arr] i=0 j = 0 while i < len(arr): if not arr2[j]: arr[i] = 0 i+=1 if i<len(arr): arr[i] = 0 else: arr[i] = arr2[j] j+=1 i+=1 return arr ob1 = Solution() print(ob1.duplicateZeros([1,0,2,3,0,4,5,0]))
Input
[1,0,2,3,0,4,5,0]
Output
[1,0,0,2,3,0,0,4]
- Related Questions & Answers
- Contains Duplicate in Python
- Add leading Zeros to Python string
- Add trailing Zeros to a Python string
- Add leading Zeros to Python Program string
- Find the Duplicate Number in Python
- Python - Replace duplicate Occurrence in String
- In-place Move Zeros to End of List in Python
- Duplicate substring removal from list in Python
- How to get a string leftpadded with zeros in Python?
- Python Pandas - Indicate duplicate index values
- Flip to Zeros in C++
- Python program to Mark duplicate elements in string
- Python – Remove Columns of Duplicate Elements
- Find keys with duplicate values in dictionary in Python
- Remove duplicate lists in tuples (Preserving Order) in Python
Advertisements