Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Move Zeroes in Array to End using Loop - Optimal Algorithm



Problem Statement

Given an array of integers, your task is to move all the zeroes to the end of the array, while maintaining the relative order of non-zero elements.

This must be done in-place without making a copy of the array, and ideally in a single pass using an optimal approach.

If the array is empty, return it as is.

Examples

Input ArrayOutput ArrayDescription
[0, 1, 0, 3, 12][1, 3, 12, 0, 0]All non-zero elements kept in order, zeroes pushed to the end
[1, 2, 3][1, 2, 3]No zeroes present, array remains unchanged
[0, 0, 0][0, 0, 0]All elements are zeroes, no changes needed
[4, 0, 5, 0, 6][4, 5, 6, 0, 0]Zeroes moved to end, non-zero order maintained
[][]Empty array, returns empty
[0][0]Single element which is zero
[9][9]Single non-zero element, unchanged
[0, 1, 0, 2, 0, 3][1, 2, 3, 0, 0, 0]Multiple interleaved zeroes correctly pushed to the end

Solution

To solve the problem of moving all zeroes in the array to the end, we need to consider several different situations. The goal is to rearrange the array so that:

  • All non-zero elements stay in the same relative order.
  • All zeroes are placed at the end.
  • The array is modified in-place, meaning we do not use extra space like a new array.

Case 1: No zeroes in the array

If there are no zeroes in the array, like in [1, 2, 3], then the array is already in the correct format. Nothing needs to be changed, and the output is the same as the input.

Case 2: All zeroes

If the array only contains zeroes, like [0, 0, 0], then there are no non-zero elements to shift. The array remains as it is.

Case 3: Zeroes scattered among non-zero elements

This is the most common case. For example, in the array [0, 1, 0, 3, 12], we want to move all the non-zero elements forward while tracking their original order: [1, 3, 12]. Once these are placed at the front, we fill the remaining slots in the array with zeroes to get the final result [1, 3, 12, 0, 0].

Case 4: Single-element array

If the array has only one element, it can either be 0 or a non-zero number. In both cases, there’s no movement needed. The array remains unchanged.

Case 5: Empty array

If the array is empty, then we simply return it as is. There’s no work to be done since there are no elements at all.

How does the optimal approach work?

The efficient way to do this is by using a pointer (let’s say nonZeroIndex) to track the position where the next non-zero element should go. As we loop through the array:

  • Every time we see a non-zero element, we place it at the nonZeroIndex and move that pointer forward.
  • Once all non-zero elements have been moved, the rest of the array (from nonZeroIndex to end) is filled with zeroes.

This approach ensures that we use only one loop to process all elements and perform the operation in-place with O(n) time and O(1) space complexity.

Visualization

Algorithm Steps

  1. Given an array of numbers arr.
  2. Initialize a pointer nonZeroIndex to 0.
  3. Iterate through each element of the array.
  4. If the element is non-zero, assign it to arr[nonZeroIndex] and increment nonZeroIndex.
  5. After the loop, fill the rest of the array from nonZeroIndex to the end with zeroes.

Code

Python
JavaScript
Java
C++
C
def move_zeroes(arr):
    nonZeroIndex = 0
    for i in range(len(arr)):
        if arr[i] != 0:
            arr[nonZeroIndex] = arr[i]
            nonZeroIndex += 1
    for i in range(nonZeroIndex, len(arr)):
        arr[i] = 0
    return arr

# Sample Input
arr = [0, 1, 0, 3, 12]
print("Result:", move_zeroes(arr))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Even if no zeros are present, the algorithm still iterates through the entire array once to check each element.
Average CaseO(n)The algorithm goes through the array once to move non-zero elements and then fills the remaining positions with zeroes.
Average CaseO(n)When all elements are zero or all are non-zero, the algorithm still performs a full scan and update in two linear passes.

Space Complexity

O(1)

Explanation: The algorithm performs all operations in-place using a constant number of variables, without using any extra space.

Detailed Step by Step Example

Let's move all zeroes to the end while maintaining the order of non-zero elements.

{ "array": [0,1,0,3,12], "showIndices": true }

Initialize nonZeroIndex = 0. We'll use this to track where the next non-zero element should go.

Check index 0

Element is 0. It's zero. Do nothing and move to next.

{ "array": [0,1,0,3,12], "showIndices": true, "highlightIndices": [0], "labels": { "0": "i", "-1": "nonZeroIndex" } }

Check index 1

Element is 1. It's non-zero, so move it to index 0.

{ "array": [1,1,0,3,12], "showIndices": true, "highlightIndices": [1], "labels": { "1": "i", "0": "nonZeroIndex" } }

Check index 2

Element is 0. It's zero. Do nothing and move to next.

{ "array": [1,1,0,3,12], "showIndices": true, "highlightIndices": [2], "labels": { "2": "i", "0": "nonZeroIndex" } }

Check index 3

Element is 3. It's non-zero, so move it to index 1.

{ "array": [1,3,0,3,12], "showIndices": true, "highlightIndices": [3], "labels": { "3": "i", "1": "nonZeroIndex" } }

Check index 4

Element is 12. It's non-zero, so move it to index 2.

{ "array": [1,3,12,3,12], "showIndices": true, "highlightIndices": [4], "labels": { "4": "i", "2": "nonZeroIndex" } }

Fill remaining positions with zeroes starting from index 3.

{ "array": [1,3,12,0,0], "showIndices": true, "labels": { "3": "start filling 0s" } }

Final Result:

[1,3,12,0,0]



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M