A chocolate factory is packing chocolates into the packets. Each packet can contain 1 or more chocolates. Recently the customer service has been getting complaints from the customers that the factory is dispatching empty chocolate packets. Your job is to identify the empty packets and push them to the end of the conveyer belt. You are given an array of N integer values denoting the number of chocolates in the packets in the same order as they are arriving on the conveyer belt. The order of the rest of the packets should be preserved.
**Input format**:
– First line: A non-negative integer N denoting the number of packets on the conveyer belt
– Second line: N space-separated integers denoting the number of chocolates present in each of those packets.
**Output format**:
– First line: N space-separated integers in the order described in the problem statement.
**Constraints:**
“`
1 <= N <= 10^5
“`
**Examples**
– Input – 1:
“`
7
4 5 0 1 9 0 5 0
“`
– Output – 1:
“`
4 5 1 9 5 0 0 0
“`
– Input – 2:
“`
7
4 5 0 1 0 0 5
“`
– Output – 2:
“`
4 5 1 5 0 0 0
Program in C
#include <stdio.h>
#include <string.h>
int main() {
unsigned int n, non_zero_size = 0;
scanf("%d", &n);
int *array = (int *) calloc (n, sizeof(int));
memset(array, 0, n);
for (unsigned int i = 0, j = 0 ; i < n; i++) {
scanf("%d", &j);
if (j != 0)
array[non_zero_size++] = j;
}
for (unsigned int i = 0 ; i < n; i++)
printf("%d ", array[i]);
return 0;
}
Program in C ( Without using Array )
#include <stdio.h>
int main() {
unsigned int n, zeroes = 0;
scanf("%d", &n);
for (unsigned int i = 0, j = 0 ; i < n; i++) {
scanf("%d", &j);
if (j != 0)
printf("%d ", j);
else
zeroes++;
}
for (unsigned int i = 0 ; i < zeroes; i++)
printf("0 ");
return 0;
}
Program in C++
#include <iostream>
int main() {
unsigned int n{0}, non_zero_size{0};
std::cin >> n;
int array[n] = {0};
for (unsigned int i = 0, j = 0 ; i < n; i++) {
std::cin >> j;
if (j != 0)
array[non_zero_size++] = j;
}
for (unsigned int i = 0 ; i < n; i++)
std::cout << array[i] << " ";
return 0;
}
Program in JAVA
import java.util.Scanner;
class Main {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int zero_count = 0, inp;
for (int i = 0 ; i < N ; i++) {
inp = in.nextInt();
if (inp == 0)
zero_count++;
else
System.out.print(inp + " ");
}
in.close();
for (int i = 0 ; i < zero_count ; i++)
System.out.print("0 ");
}
}
Program in Python
if __name__ == "__main__":
N = int(input())
zero_count = 0
for i in input().split():
if i == '0':
zero_count += 1
else:
print(i, end = ' ')
for i in range(zero_count):
print('0', end = ' ')
Pingback: TCS NQT CODING QUESTIONS WITH SOLUTIONS - GRAD JOB OPENINGS