Move Zeros to End

TCS NQT Coding Easy Go Ad-Free - ₹20/mo

Given an array of integers representing chocolate packets, where 0 indicates an empty packet, the task is to move all empty packets (zeros) to the end of the array while maintaining the relative order of the non-empty packets.

Examples:

Input: N = 8, arr = [4, 5, 0, 1, 9, 0, 5, 0]

Output: [4, 5, 1, 9, 5, 0, 0, 0]

Explanation: The three zeros are moved to the end, and the non-zero elements retain their original order.

Input: N = 5, arr = [0, 1, 0, 3, 12]

Output: [1, 3, 12, 0, 0]

Explanation: Zeros are moved to the end, and non-zero elements keep their order.

Input: N = 3, arr = [0, 0, 1]

Output: [1, 0, 0]

Explanation: The non-zero element is moved to the front, and zeros to the end.

Constraints

  • 1 ≤ N ≤ 10^5
  • -10^9 ≤ arr[i] ≤ 10^9
  • Array elements are integers