TCS NQT Coding Question-1: Factory empty packets

TCS NQT Coding Question-1: Factory empty packets

In this post, we will see the solution of the Python Coding Question which is already asked in the TCS NQT Exam.

Problem Statement: A factory is packing candies into the packets. The candies packets here represent an array of N number of integer values. The task is to find the empty packets(0) of candies and push it to the end of the conveyor belt(array).

Example 1 :

N=10 and arr = [40,50,0,10,90,0,50,0,65,0].

There are 4 empty packets in the given set. These 4 empty packets represented as 0 should be pushed towards the end of the array

Input :

10 – Value of N

[40,50,0,10,90,0,50,0,65,0] – Element of arr[O] to arr[N-1]

Output:

40 50 10 90 50 65 0 0 0 0

Example 2:

N=6 and arr = [6,0,1,8,0,2].

There are 2 empty packets in the given set. These 2 empty packets represented as 0 should be pushed towards the end of the array

Input:

6 — Value of N.

[6,0,1,8,0,2] – Element of arr[0] to arr[N-1]

Output:

6 1 8 2 0 0

Solution 1:

# taking inputs
N = int(input())
arr = list(map(int, input().split()))

# empty list created
non_zero_arr = []
zero_arr = []

# Iterate through the list to collect all non-zero
# and zero elements separately in the list
for packet in arr :

    # non-zero element check
    if packet :
        non_zero_arr.append(packet)
    else :
        zero_arr.append(packet)

# concatenating both the list
result_arr = non_zero_arr + zero_arr

print(result_arr)

Output:

8
40 50 0 10 90 0 50 0
[40, 50, 10, 90, 50, 0, 0, 0]

Solution 2:

# taking inputs
N = int(input())
arr = list(map(int, input().split()))

# Iterate through the list to collect all non-zero element
non_zero_arr = [packet for packet in arr if packet]

# number of zeros count 
zeros_count = arr.count(0)

# concatenating both the list
result_arr = non_zero_arr + [0] * zeros_count

print(result_arr)

Output:

8
40 50 0 1 9 0 5 0
[40, 50, 1, 9, 5, 0, 0, 0]

Both time and space complexity for the above solutions is O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds