mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-22 16:31:15 -04:00
Update and rename array-duplicate-zeros.py to duplicate_zeros_inplace.py
This commit is contained in:
parent
5c0e0228e6
commit
761c1f0670
1 changed files with 1 additions and 11 deletions
27
arrays_and_strings/duplicate_zeros_inplace.py
Normal file
27
arrays_and_strings/duplicate_zeros_inplace.py
Normal file
|
@ -0,0 +1,27 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
# Given a fixed-length integer array arr, duplicate each occurrence of zero,
|
||||
# shifting the remaining elements to the right.
|
||||
|
||||
|
||||
def duplicate_zeros(arr: list[int]) -> list[int]:
|
||||
|
||||
i = 0
|
||||
while i < len(arr):
|
||||
|
||||
if arr[i] == 0 and i != len(arr) - 1:
|
||||
|
||||
range_here = len(arr) - (i + 2)
|
||||
while range_here > 0:
|
||||
arr[i + range_here + 1] = arr[i + range_here]
|
||||
range_here -= 1
|
||||
|
||||
arr[i+1] = 0
|
||||
i += 2
|
||||
|
||||
else:
|
||||
i += 1
|
||||
|
||||
return arr
|
Loading…
Add table
Add a link
Reference in a new issue