fork download
  1. def push_zeros_to_end(arr):
  2. # Index to place the next non-zero element
  3. non_zero_index = 0
  4.  
  5. # Traverse the array
  6. for i in range(len(arr)):
  7. if arr[i] != 0:
  8. # Swap non-zero element with the element at non_zero_index
  9. arr[non_zero_index], arr[i] = arr[i], arr[non_zero_index]
  10. non_zero_index += 1
  11.  
  12. return arr
  13.  
  14. # Example usage
  15. array = [0, 1, 0, 3, 12]
  16. result = push_zeros_to_end(array)
  17. print(result) # Output: [1, 3, 12, 0, 0]
  18.  
Success #stdin #stdout 0.03s 25824KB
stdin
Standard input is empty
stdout
def push_zeros_to_end(arr):
    # Index to place the next non-zero element
    non_zero_index = 0

    # Traverse the array
    for i in range(len(arr)):
        if arr[i] != 0:
            # Swap non-zero element with the element at non_zero_index
            arr[non_zero_index], arr[i] = arr[i], arr[non_zero_index]
            non_zero_index += 1

    return arr

# Example usage
array = [0, 1, 0, 3, 12]
result = push_zeros_to_end(array)
print(result)  # Output: [1, 3, 12, 0, 0]