Binary TreesBinary Trees36
  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Inorder Traversal of a Binary Tree using Recursion
  4. 4Inorder Traversal of a Binary Tree using Iteration
  5. 5Postorder Traversal of a Binary Tree Using Recursion
  6. 6Postorder Traversal of a Binary Tree using Iteration
  7. 7Level Order Traversal of a Binary Tree using Recursion
  8. 8Level Order Traversal of a Binary Tree using Iteration
  9. 9Reverse Level Order Traversal of a Binary Tree using Iteration
  10. 10Reverse Level Order Traversal of a Binary Tree using Recursion
  11. 11Find Height of a Binary Tree
  12. 12Find Diameter of a Binary Tree
  13. 13Find Mirror of a Binary Tree
  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
GraphsGraphs46
  1. 1Breadth-First Search in Graphs
  2. 2Depth-First Search in Graphs
  3. 3Number of Provinces in an Undirected Graph
  4. 4Connected Components in a Matrix
  5. 5Rotten Oranges Problem - BFS in Matrix
  6. 6Flood Fill Algorithm - Graph Based
  7. 7Detect Cycle in an Undirected Graph using DFS
  8. 8Detect Cycle in an Undirected Graph using BFS
  9. 9Distance of Nearest Cell Having 1 - Grid BFS
  10. 10Surrounded Regions in Matrix using Graph Traversal
  11. 11Number of Enclaves in Grid
  12. 12Word Ladder - Shortest Transformation using Graph
  13. 13Word Ladder II - All Shortest Transformation Sequences
  14. 14Number of Distinct Islands using DFS
  15. 15Check if a Graph is Bipartite using DFS
  16. 16Topological Sort Using DFS
  17. 17Topological Sort using Kahn's Algorithm
  18. 18Cycle Detection in Directed Graph using BFS
  19. 19Course Schedule - Task Ordering with Prerequisites
  20. 20Course Schedule 2 - Task Ordering Using Topological Sort
  21. 21Find Eventual Safe States in a Directed Graph
  22. 22Alien Dictionary Character Order
  23. 23Shortest Path in Undirected Graph with Unit Distance
  24. 24Shortest Path in DAG using Topological Sort
  25. 25Dijkstra's Algorithm Using Set - Shortest Path in Graph
  26. 26Dijkstra’s Algorithm Using Priority Queue
  27. 27Shortest Distance in a Binary Maze using BFS
  28. 28Path With Minimum Effort in Grid using Graphs
  29. 29Cheapest Flights Within K Stops - Graph Problem
  30. 30Number of Ways to Reach Destination in Shortest Time - Graph Problem
  31. 31Minimum Multiplications to Reach End - Graph BFS
  32. 32Bellman-Ford Algorithm for Shortest Paths
  33. 33Floyd Warshall Algorithm for All-Pairs Shortest Path
  34. 34Find the City With the Fewest Reachable Neighbours
  35. 35Minimum Spanning Tree in Graphs
  36. 36Prim's Algorithm for Minimum Spanning Tree
  37. 37Disjoint Set (Union-Find) with Union by Rank and Path Compression
  38. 38Kruskal's Algorithm - Minimum Spanning Tree
  39. 39Minimum Operations to Make Network Connected
  40. 40Most Stones Removed with Same Row or Column
  41. 41Accounts Merge Problem using Disjoint Set Union
  42. 42Number of Islands II - Online Queries using DSU
  43. 43Making a Large Island Using DSU
  44. 44Bridges in Graph using Tarjan's Algorithm
  45. 45Articulation Points in Graphs
  46. 46Strongly Connected Components using Kosaraju's Algorithm

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 Array Output Array Description
[0, 1, 0, 3, 12] [1, 3, 12, 0, 0] All non-zero elements kept in order, zeroes pushed to the endVisualization
[1, 2, 3] [1, 2, 3] No zeroes present, array remains unchangedVisualization
[0, 0, 0] [0, 0, 0] All elements are zeroes, no changes neededVisualization
[4, 0, 5, 0, 6] [4, 5, 6, 0, 0] Zeroes moved to end, non-zero order maintainedVisualization
[] [] Empty array, returns emptyVisualization
[0] [0] Single element which is zeroVisualization
[9] [9] Single non-zero element, unchangedVisualization
[0, 1, 0, 2, 0, 3] [1, 2, 3, 0, 0, 0] Multiple interleaved zeroes correctly pushed to the endVisualization

Visualization Player

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.

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.
Worst 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]