Home

Shifiting a list


def shifting_zeros(arr):
    for elem in arr:
        if elem == 0:
            arr.remove(elem)
            arr.append(0)
    return arr



def better_function(arr):
    temp = []
    z = 0
    for elem in arr:
        if elem != 0:
            temp.append(elem)
        else:
            z = z + 1
    temp.extend(z * [0])
    return temp


import random
import time

n = 200_000
array = [random.randint(0, 9) for _ in range(n)]

start = time.time()
x = shifting_zeros(array)
stop = time.time()
print(stop-start) 
# --> around 100 sec


start = time.time()
x = better_function(array)
stop = time.time()
print(stop-start) 
# ---> below 1 sec

Shifting zeros function

The function iterates over each element in the input array. If an element is 0, it removes that element from the array (arr.remove(elem)), which is O(n) in complexity because list.remove searches for the element. Then, it appends 0 to the end of the array (arr.append(0)), which is O(1).

Time Complexity:

Space Complexity:

Detaild explanation

The list.remove(elem) operation in Python takes O(n) time because it involves the following steps:

  1. Search for the Element:

When you call arr.remove(elem), Python first scans the list to locate the first occurrence of elem. This involves a linear search through the list, which has a worst-case complexity of O(n) where n is the length of the list.

For example, in the list [1, 2, 3, 0, 4], if you call arr.remove(0), Python must iterate over the first three elements (1, 2, and 3) before it finds the 0.

  1. Shift Elements After Removal:

Once the element is found and removed, all the elements after the removed element need to be shifted one position to the left to fill the gap.

For example, if you remove the 0 from [1, 2, 0, 3, 4], the list is updated like this: [1, 2, 3, 4]

This shifting operation also takes O(n) time in the worst case, depending on how many elements follow the removed element.

“Better function” function

Time Complexity:

Space Complexity:

Tags: Python, Data_structures, List, Data_structures_in_action