Skip to content

Commit 105e89d

Browse files
committed
283. Move Zeroes.
- Language: Python. - Time complexity: O(2n). - Space complexity: O(1). - Solution: https://www.geeksforgeeks.org/problems/move-all-zeroes-to-end-of-array0751/1
1 parent ab3bdcd commit 105e89d

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

python_solutions/lc_283_move_zeroes/lc_283.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,20 @@ def moveZeroesV3(self, nums: list[int]) -> None:
5656
# Copy all the elements from temp[] to arr[]
5757
for i in range(n):
5858
nums[i] = temp[i]
59+
60+
def moveZeroesV4(self, nums: list[int]) -> None:
61+
# Time complexity: O(2n). Space complexity: O(1).
62+
# Solution: https://www.geeksforgeeks.org/problems/move-all-zeroes-to-end-of-array0751/1
63+
# Count of non-zero elements
64+
count = 0
65+
# If the element is non-zero, replace the element at
66+
# index 'count' with this element and increment count
67+
for i in range(len(nums)):
68+
if nums[i] != 0:
69+
nums[count] = nums[i]
70+
count += 1
71+
# Now all non-zero elements have been shifted to
72+
# the front. Make all elements 0 from count to end.
73+
while count < len(nums):
74+
nums[count] = 0
75+
count += 1

python_solutions/lc_283_move_zeroes/test_lc_283.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,15 @@ def test_success_v3(nums: list[int], ans: set[int], solution: Solution):
8383
assert id(nums) == nums_id
8484

8585

86+
@pytest.mark.parametrize(("nums", "ans"), test_cases)
87+
def test_success_v4(nums: list[int], ans: set[int], solution: Solution):
88+
nums_id = id(nums)
89+
solution.moveZeroesV3(nums)
90+
assert nums == ans
91+
assert nums == ans
92+
assert id(nums) == nums_id
93+
94+
8695
@pytest.fixture
8796
def solution() -> Solution:
8897
return Solution()

0 commit comments

Comments
 (0)