TCS NQT Practice Coding Questions and Answers

Sample Practice Coding Questions for TCS NQT

On this page you are going to see TCS NQT Coding Questions along with Answers to practice in the following languages:

  • C
  • C++
  • Java
  • Python

TCS NQT Advanced Section

TCS NQT Coding Practice Questions

Day 1 – Slot 1 – Question 1:

Problem Statement –

A chocolate factory is packing chocolates into the packets. The chocolate packets here represent an array of N number of integer values. The task is to find the empty packets(0) of chocolate and push them to the end of the conveyor belt(array).

Example 1 :

N=8 and arr = [4,5,0,1,9,0,5,0].

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

Input :

8  – Value of N

[4,5,0,1,9,0,5,0] – Element of arr[O] to arr[N-1],While input each element is separated by newline

Output:

4 5 1 9 5 0 0 0

Example 2:

Input:

6 — Value of N.

[6,0,1,8,0,2] – Element of arr[0] to arr[N-1], While input each element is separated by newline

Output:

6 1 8 2 0 0

Solution in C:

#include <stdio.h>
int main()
{
  int n, j = 0;
  scanf("%d", &n);
  int a[n];
  for (int i = 0; i < n; i++)
  {
    scanf("%d", &a[j]);
    if (a[j] != 0)
    {
        j++;
    }
  }
  for (int i = 0; i < j; i++)
  {
      printf("%d ", a[i]);
  }
  return 0;
}

Solution in C++:

#include <bits/stdc++.h>
using namespace std;
int main ()
{
  int n, j = 0;
  cin >> n;
  int a[n] = { 0 };
  for (int i = 0; i < n; i++)
  {
    cin >> a[j];
    if (a[j] != 0)
    {
        j++;
    }
  }
  for (int i = 0; i < n; i++)
  {
      cout << a[i] << " ";
  }
}

Solution in Java:

import java.util.*;
class Main
{
    public static void main(String[] args)
    {
            Scanner sc=new Scanner(System.in);
            int n=sc.nextInt();
            int arr[]=new int[n];
            for(int i=0;i< n;i++)
                  arr[i]=sc.nextInt();
            int count=0;
            for(int i=0;i< n;i++)
                if(arr[i]!=0)
                    arr[count++]=arr[i];
             for(int i=count;i < n;i++)
                 arr[i]=0;
             for(int i=0;i< n;i++)
                    System.out.print(arr[i]+" ");
    }
}

Solution in Python:

n=int(input())
j=0
L=[0 for i in range(n)]
for i in range(n):
    a=int(input())
    if a!=0:
        L[j]=a
        j+=1
for i in L:
    print(i,end=" ")

Day 1 – Slot 1 – Question 2:

Problem Statement –

Joseph is learning digital logic subject which will be for his next semester. He usually tries to solve unit assignment problems before the lecture. Today he got one tricky question. The problem statement is “A positive integer has been given as an input. Convert decimal value to binary representation. Toggle all bits of it after the most significant bit including the most significant bit. Print the positive integer value after toggling all bits”.

Constrains-

1<=N<=100

Example 1 :

Input :

10  -> Integer

Output :

5    -> result- Integer

Explanation:

Binary representation of 10 is 1010. After toggling the bits(1010), will get 0101 which represents “5”. Hence output will print “5”.

Solution in C:

#include <stdio.h>
#include <math.h>
int main()
{
    int n;
    scanf("%d", &n);
    int k = (1 << (int)(log2(n) + 1)) - 1;
    printf("%d", n ^ k);
    return 0;
}

Solution in C++:

#include<bits/stdc++.h>
using namespace std;
int main ()
{
  int n;
  cin >> n;
  int k = (1 << (int) floor (log2 (n)) + 1) - 1;
  cout << (n ^ k);
}

Solution in Java:

import java.util.*;
class Main
{
  public static void main(String[] args)
  {
         Scanner sc=new Scanner(System.in);
         int no=sc.nextInt();
          String bin="";
         
          while(no!=0)
           {
                  bin=(no&1)+bin;
                  no=no>>1;
           }
            bin=bin.replaceAll("1","2");
            bin=bin.replaceAll("0","1");
            bin=bin.replaceAll("2","0");
            int res=Integer.parseInt(bin,2);
           System.out.println(res);
   }
}

Solution in Python:

import math
n=int(input())
k=(1<< int(math.log2(n))+1)-1
print(n^k)

Day 1 – Slot 2 – Question 1

Problem Statement –

Jack is always excited about sunday. It is favourite day, when he gets to play all day. And goes to cycling with his friends.

So every time when the months starts he counts the number of sundays he will get to enjoy. Considering the month can start with any day, be it Sunday, Monday…. Or so on.

Count the number of Sunday jack will get within n number of days.

Example 1 :

N=8 and arr = [4,5,0,1,9,0,5,0].

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

Input :

Input 

mon-> input String denoting the start of the month.

13  -> input integer denoting the number of days from the start of the month.

Output :

2    -> number of days within 13 days.

Explanation:

The month start with mon(Monday). So the upcoming sunday will arrive in next 6 days. And then next Sunday in next 7 days and so on.

Now total number of days are 13. It means 6 days to first sunday and then remaining 7 days will end up in another sunday. Total 2 sundays may fall within 13 days.

Solution in C:

#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 4
int main()
{
    char s[MAX_LENGTH];
    scanf("%s", s);

    int a, ans = 0;
    scanf("%d", &a);

    // Map weekdays to their corresponding values
    char weekdays[][MAX_LENGTH] = {
        "mon", "tue", "wed", "thu", "fri", "sat", "sun"
    };
    int values[] = {6, 5, 4, 3, 2, 1, 0};

    // Find the corresponding value for the input weekday
    int mapSize = sizeof(weekdays) / sizeof(weekdays[0]);
    int m = -1;
    for (int i = 0; i < mapSize; i++) {
        if (strcmp(s, weekdays[i]) == 0) {
            m = values[i];
            break;
        }
    }

    if (m != -1) {
        // Calculate the answer
        if (a - m >= 1) {
            ans = 1 + (a - m) / 7;
        }
    }
    
    printf("%d", ans);

    return 0;
}

Solution in C++:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s; cin>>s;
    int a,ans=0;
    cin>>a;
    unordered_map< string,int > m;
    m["mon"]=6;m["tue"]=5;m["wed"]=4;
    m["thu"]=3;m["fri"]=2;m["sat"]=1;
    m["sun"]=0;
    if(a-m[s.substr(0,3)] >=1) ans=1+(a-m[s.substr(0,3)])/7;
    cout<< ans;
}

Solution in Java:

import java.util.*;
class Main
{
public static void main(String[] args)
{
        Scanner sc=new Scanner(System.in);
        String str=sc.next();
        int n=sc.nextInt();
        String arr[]={"mon","tue,","wed","thu","fri","sat","sun"};
        int i=0;
        for(i=0;i< arr.length;i++)
             if(arr[i].equals(str))
                 break;
        int res=1;
        int rem=6-i;
        n=n-rem;    
        if(n >0)
           res+=n/7;
        System.out.println(res);
      
}
}
Solution in Python:
def main():
    s = input()
    a = int(input())
    m = {
        "mon": 6, "tue": 5, "wed": 4,
        "thu": 3, "fri": 2, "sat": 1,
        "sun": 0
    }
    ans = 0
    if a - m[s[:3]] >= 1:
        ans = 1 + (a - m[s[:3]]) // 7
    print(ans)

if __name__ == "__main__":
    main()

Day 1 – Slot 2 – Question 2

Problem Statement –

Airport security officials have confiscated several item of the passengers at the security check point. All the items have been dumped into a huge box (array). Each item possesses a certain amount of risk[0,1,2]. Here, the risk severity of the items represent an array[] of N number of integer values. The task here is to sort the items based on their levels of risk in the array. The risk values range from 0 to 2.
Example 1 :

Input :

7  -> Value of N

[1,0,2,0,1,0,2]-> Element of arr[0] to arr[N-1], while input each element is separated by new line.

Output :

0 0 0 1 1 2 2  -> Element after sorting based on risk severity

Example 2:

input : 10  -> Value of N

[2,1,0,2,1,0,0,1,2,0] -> Element of arr[0] to arr[N-1], while input each element is separated by a new line.

Output : 

0 0 0 0 1 1 1 2 2 2  ->Elements after sorting based on risk severity.

Explanation:

In the above example, the input is an array of size N consisting of only 0’s, 1’s and 2s. The output is a sorted array from 0 to 2 based on risk severity.

Solution in C:

#include<stdio.h> 
void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void sortArray(int arr[], int size) {
    int low = 0, mid = 0, high = size - 1;
    while (mid <= high) {
        if (arr[mid] == 0) {
            swap(&arr[low], &arr[mid]);
            low++;
            mid++;
        } else if (arr[mid] == 1) {
            mid++;
        } else {
            swap(&arr[mid], &arr[high]);
            high--;
        }
    }
}

int main() {
    int n;
    scanf("%d", &n);
    int a[n];
    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    sortArray(a, n);
    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    return 0;
}

Solution in C++:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n; cin>>n;
    int a[n];
    for(int i=0;i< n;i++) cin>>a[i];
    int l=0,m=0,h=n-1;
    while(m<=h)
    {
        if(a[m]==0) swap(a[l++],a[m++]);
        else if(a[m]==1) m++;
        else swap(a[m],a[h--]);
    }
    for(int i=0;i< n;i++) cout<< a[i]<<" ";
}

Solution in Java:

import java.util.*;
class Main
{
    public static void main(String[] args)
    {
         Scanner sc=new Scanner(System.in);
          int n=sc.nextInt();
          int arr[]=new int[n];
          for(int i=0;i< n;i++)
                 arr[i]=sc.nextInt();
           int countZero=0,countOne=0,countTwo=0;
           for(int i=0;i< n;i++) { if(arr[i]==0) countZero++; else if(arr[i]==1) countOne++; else if(arr[i]==2) countTwo++; } int j =0; while(countZero >0)
             {
                        arr[j++]=0;
                        countZero--;
             }
             while(countOne >0)
             {
                       arr[j++]=1;
                      countOne--;
              }

              while(countTwo >0)
              {
                      arr[j++]=2;
                      countTwo--;
               }

              for(int i=0;i < n;i++)
                    System.out.print(arr[i]+" ");        
    }
}

Solution in Python:

n = int(input())
arr = []
for i in range(n):
    arr.append(int(input()))
for i in sorted(arr):
    print(i, end=" ")

Day 2 – Slot 1 – Question 1

Problem Statement –

Given an integer array Arr of size N the task is to find the count of elements whose value is greater than all of its prior elements.

Note : 1st element of the array should be considered in the count of the result.

For example,

Arr[]={7,4,8,2,9}

As 7 is the first element, it will consider in the result.

8 and 9 are also the elements that are greater than all of its previous elements.

Since total of  3 elements is present in the array that meets the condition.

Hence the output = 3.

Example 1:

Input 

5 -> Value of N, represents size of Arr

7-> Value of Arr[0]

4 -> Value of Arr[1]

8-> Value of Arr[2]

2-> Value of Arr[3]

9-> Value of Arr[4]

Output :

3

Example 2:

5   -> Value of N, represents size of Arr

3  -> Value of Arr[0]

4 -> Value of Arr[1]

5 -> Value of Arr[2]

8 -> Value of Arr[3]

9 -> Value of Arr[4]

Output : 

5

Constraints

1<=N<=20

1<=Arr[i]<=10000

Solution in C:

#include<stdio.h> 
#include<limits.h> 

int main() {
    int n, c = 0, a, m = INT_MIN;
    scanf("%d", &n);
    while (n--) {
        scanf("%d", &a);
        if (a >= m) {
            m = a;
            c++;
        }
    }
    printf("%d", c);
    return 0;
}

Solution in C++:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n,c=0,a,m=INT_MIN;
    cin>>n;
    while(n--)
    {
        cin>>a;
        if(a>m)
        {
            m=a;
            c++;
        }
    }
    cout << c;
}

Solution in Java:

import java.util.*;
class Main
{
  public static void main(String[] args)
  {
         Scanner sc=new Scanner(System.in);
         int n=sc.nextInt();
         int arr[]=new int[n];
         for(int i=0;i< n;i++)
                 arr[i]=sc.nextInt();
         int max=Integer.MIN_VALUE;

         int count=0;
         for(int i=0;i< n;i++) { if(arr[i]>max)

              {
                       max=arr[i];
                       count++;
               }
         }      
         System.out.println(count);
}
}

Solution in Python:

import sys
n=int(input())
c=0
m=-sys.maxsize-1
while n:
    n-=1
    a=int(input())
    if a>m:
        m=a
        c+=1
print(c)

Day 2 – Slot 1 – Question 2

Problem Statement –

A supermarket maintains a pricing format for all its products. A value N is printed on each product. When the scanner reads the value N on the item, the product of all the digits in the value N is the price of the item. The task here is to design the software such that given the code of any item N the product (multiplication) of all the digits of value should be computed(price).

Example 1:

Input :

5244 -> Value of N

Output :
160 -> Price

Explanation:

From the input above

Product of the digits 5,2,4,4

5*2*4*4= 160

Hence, output is 160.

Solution in C:

#include<stdio.h> 
#include<limits.h>

int main() {
    char s[100];
    scanf("%s", s);
    int p = 1;
    for (int i = 0; i < strlen(s); i++) {
        p *= (s[i] - '0');
    }
    printf("%d", p);
    return 0;
}

Solution in C++:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s; 
    cin>>s;
    int p=1;
    for(auto i:s) 
        p*=(i-'0');
    cout<< p;
}

Solution in Java:

import java.util.*;
class Main
{
    public static void main(String[] args)
    {
          Scanner sc=new Scanner(System.in);
          int n=sc.nextInt();
          int res=1;
          while(n>0)
          {
                res=res*(n%10);
                n=n/10;
           }
            System.out.println(res);
    }
}

Solution in Python:

n=input()
p=1
for i in n:
    p*=int(i)
print(p)

Day 3 – Slot 2 – Question 1

Problem Statement –

A furnishing company is manufacturing a new collection of curtains. The curtains are of two colors aqua(a) and black (b). The curtains color is represented as a string(str) consisting of a’s and b’s of length N. Then, they are packed (substring) into L number of curtains in each box. The box with the maximum number of ‘aqua’ (a) color curtains is labeled. The task here is to find the number of ‘aqua’ color curtains in the labeled box.

Note :

If ‘L’ is not a multiple of N, the remaining number of curtains should be considered as a substring too. In simple words, after dividing the curtains in sets of ‘L’, any curtains left will be another set(refer example 1)

Example 1:

Input :

bbbaaababa -> Value of str

3    -> Value of L

Output:

3   -> Maximum number of a’s

Explanation:

From the input given above.

Dividing the string into sets of 3 characters each

Set 1: {b,b,b}

Set 2: {a,a,a}

Set 3: {b,a,b}

Set 4: {a} -> leftover characters also as taken as another set

Among all the sets, Set 2 has more number of a’s. The number of a’s in set 2 is 3.

Hence, the output is 3.

Example 2:

Input :

abbbaabbb -> Value of str

5   -> Value of L

Output:

2   -> Maximum number of a’s

Explanation:

From the input given above,

Dividing the string into sets of 5 characters each.

Set 1: {a,b,b,b,b}

Set 2: {a,a,b,b,b}

Among both the sets, set 2 has more number of a’s. The number of a’s in set 2 is 2.

Hence, the output is 2.

Constraints:

1<=L<=10

1<=N<=50

The input format for testing

The candidate has to write the code to accept two inputs separated by a new line.

First input- Accept string that contains character a and b only

Second input- Accept value for N(Positive integer number)

The output  format for testing

The output should be a positive integer number of print the message(if any) given in the problem statement.(Check the output in Example 1, Example 2).

Solution in C:

#include<stdio.h>
#include<string.h>

int main() {
    char str[100];
    scanf("%s", str);
    int n;
    scanf("%d", &n);
    int max = 0, count = 0;
    for (int i = 0; i < strlen(str); i++) { if (i % n == 0) { if (count > max)
                max = count;
            count = 0;
        }
        if (str[i] == 'a')
            count++;
    }
    if (count > max)
        max = count;
    printf("%d\n", max);
    return 0;
}

Solution in C++:

#include<bits/stdc++.h> 
using namespace std;

int main() {
    string str;
    cin >> str;
    int n;
    cin >> n;
    int max = 0, count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (i % n == 0) {
            max = std::max(count, max);
            count = 0;
        }
        if (str[i] == 'a')
            count++;
    }
    max = std::max(count, max);
    cout << max << endl;
    return 0;
}

Solution in Java:

import java.util.*;
class Main
{
       public static void main(String[] args)
       {
               Scanner sc=new Scanner(System.in);
               String str=sc.next();
               int n=sc.nextInt();
               int max=0,count=0;
               for(int i=0;i< str.length();i++)
               {
                       if(i%n==0)
                       {
                          max=Math.max(count,max); 
                          count=0;
                       }
                       if(str.charAt(i)=='a')
                             count++;
                }
                max=Math.max(count,max);
                System.out.println(max);     
       }
}

Solution in Python:

str = input()
n = int(input())
max_val = 0
count = 0
for i in range(len(str)):
    if i % n == 0:
        max_val = max(count, max_val)
        count = 0
    if str[i] == 'a':
        count += 1
if count > max_val:
    max_val = count
print(max_val)

Day 3 – Slot 2 – Question 2

Problem Statement –

An international round table conference will be held in india. Presidents from all over the world representing their respective countries will be attending the conference. The task is to find the possible number of ways(P) to make the N members sit around the circular table such that.

The president and prime minister of India will always sit next to each other.

Example 1:

Input :

4   -> Value of N(No. of members)

Output : 

12  -> Possible ways of seating the members

Explanation:

2  members should always be next to each other.

So, 2 members can be in 2!ways

Rest of the members can be arranged in (4-1)! ways.(1 is subtracted because the previously selected two members will be considered as single members now).

So total possible ways 4 members can be seated around the circular table 2*6= 12.

Hence, output is 12.

Example 2:

Input:

10  -> Value of N(No. of members)

Output :

725760 -> Possible ways of seating the members

Explanation:

2 members should always be next to each other.

So, 2 members can be in 2! ways

Rest of the members can be arranged in (10-1)! Ways. (1 is subtracted because the previously selected two members will be considered as a single member now).

So, total possible ways 10 members can be seated around a round table is

2*362880 = 725760 ways.

Hence, output is 725760.

The input format for testing

The candidate has to write the code to accept one input

First input – Accept value of number of N(Positive integer number)

The output format for testing

The output should be a positive integer number or print the message(if any) given in the problem statement(Check the output in example 1, example2)

Constraints :

2<=N<=50

Solution in C:

#include<stdio.h> 
int main() {
    int n;
    scanf("%d", &n);
    int fact[n + 1];
    fact[0] = 1;
    for (int i = 1; i <= n; i++) {
        fact[i] = fact[i - 1] * i;
    }
    printf("%d\n", fact[n - 1] * 2);
    return 0;
}

Solution in C++:

#include<bits/stdc++.h>
using namespace std;
int main() {
    int n;
    cin >> n;
    vector fact(n + 1, 1);
    for (int i = 1; i <= n; i++) {
        fact[i] = fact[i - 1] * i;
    }
    cout << fact[n - 1] * 2 << endl;
    return 0;
}

Solution in Java:

import java.math.BigInteger;
import java.util.*;
class Main
{
       public static BigInteger fact(int number)
      {
           BigInteger res= BigInteger.ONE;
           for (int i = number; i > 0; i--)
                 res = res.multiply(BigInteger.valueOf(i));
           return res;
      }
      public static void main(String[] args)
     {
           Scanner sc=new Scanner(System.in);
           int n=sc.nextInt();
           BigInteger res=fact(n-1);
           System.out.println(res.multiply(BigInteger.valueOf(2)));    
     }
}

Solution in Python:

n = int(input())
fact = [0] * (n + 1)
fact[0] = 1
for i in range(1, n + 1):
    fact[i] = fact[i - 1] * i
print(fact[n - 1] * 2)

Day 4 – Slot 1- Question 1

Problem Statement

An intelligence agency has received reports about some threats. The reports consist of numbers in a mysterious method. There is a number “N” and another number “R”. Those numbers are studied thoroughly and it is concluded that all digits of the number ‘N’ are summed up and this action is performed ‘R’ number of times. The resultant is also a single digit that is yet to be deciphered. The task here is to find the single-digit sum of the given number ‘N’ by repeating the action ‘R’ number of times.

If the value of ‘R’ is 0, print the output as ‘0’.

Example 1:

Input :

99 -> Value of N

3  -> Value of R

Output :

9  -> Possible ways to fill the cistern.

Explanation:

Here, the number N=99

  1. Sum of the digits N: 9+9 = 18
  2. Repeat step 2 ‘R’ times i.e. 3 tims  (9+9)+(9+9)+(9+9) = 18+18+18 =54
  3. Add digits of 54 as we need a single digit 5+4

Hence , the output is 9.

Example 2:

Input :

1234   -> Value of N

2      -> Value of R

Output :

2  -> Possible ways to fill the cistern

Explanation:

Here, the number N=1234

  1. Sum of the digits of N: 1+2+3+4 =10
  2. Repeat step 2 ‘R’ times i.e. 2 times  (1+2+3+4)+(1+2+3+4)= 10+10=20
  3. Add digits of 20 as we need a single digit. 2+0=2

Hence, the output is 2.

Constraints:

0<N<=1000

0<=R<=50

The Input format for testing

The candidate has to write the code to accept 2 input(s)

First input- Accept value for N (positive integer number)

Second input: Accept value for R(Positive integer number)

The output format for testing

The output should be a positive integer number or print the message (if any) given in the problem statement. (Check the output in Example 1, Example 2).

Solution in C:

#include<stdio.h>
#include<string.h>
int main() {
    char s[100];
    scanf("%s", s);
    int n, sum = 0;
    scanf("%d", &n);
    for (int i = 0; i < strlen(s); i++) { sum += (s[i] - '0'); } sum *= n; sprintf(s, "%d", sum); while (strlen(s) > 1) {
        sum = 0;
        for (int i = 0; i < strlen(s); i++) {
            sum += (s[i] - '0');
        }
        sprintf(s, "%d", sum);
    }
    printf("%s", s);
    return 0;
}

Solution in C++:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s; cin>>s;
    int n,sum=0; cin>>n;
    for(auto i:s) sum+=(i-'0');
    sum*=n;
    s=to_string(sum);
    while(s.length()>1)
    {
        sum=0;
        for(auto i:s) sum+=(i-'0');
        s=to_string(sum);
    }
    cout<< s;
}

Solution in Java:

import java.util.*;
class Main
{
       public static int sumOfDigits(int n)
       {
             int sum=0;
             while(n>0)
             {
                  sum+=n%10;
                  n=n/10;
             }
           return sum;
        }
        public static void main(String []args)
        {
              Scanner sc=new Scanner(System.in);
              int n=sc.nextInt();
              int r=sc.nextInt();
              if(r==0)
                    System.out.println("0");
              else
              {
                       int res=sumOfDigits(n)*r;
                       int sum=0;
                       while(true)
                       {
                               while(res>0)
                             {
                                    sum=sum+res%10;
                                    res=res/10;
                              }
                              if((sum/10)==0)
                                 break;
                              else
                                 res=sum;
                      }
                      System.out.println(sum);
                }  
        } }

Solution in Python:

s=input()
n=int(input())
sum=0
for i in s:
    sum+=int(i)
sum*=n
s=str(sum)
while len(s)>1:
    sum=0
    for i in s:
        sum+=int(i)
    s=str(sum)

print(s)

Day 4 – Slot 1- Question 2

Problem Statement

Particulate matters are the biggest contributors to Delhi pollution. The main reason behind the increase in the concentration of PMs include vehicle emission by applying Odd Even concept for all types of vehicles. The vehicles with the odd last digit in the registration number will be allowed on roads on odd dates and those with even last digit will on even dates.

Given an integer array a[], contains the last digit of the registration number of N vehicles traveling on date D(a positive integer). The task is to calculate the total fine collected by the traffic police department from the vehicles violating the rules.

Note : For violating the rule, vehicles would be fined as X Rs.

Example 1:

Input :

4 -> Value of N

{5,2,3,7} -> a[], Elements a[0] to a[N-1], during input each element is separated by a new line

12 -> Value of D, i.e. date

200 -> Value of x i.e. fine

Output :

600  -> total fine collected

Explanation:

Date D=12 means , only an even number of vehicles are allowed.

Find will be collected from 5,3 and 7 with an amount of 200 each.

Hence, the output = 600.

Example 2:

Input :

5   -> Value of N

{2,5,1,6,8}  -> a[], elements a[0] to a[N-1], during input each element is separated by new line

3 -> Value of D i.e. date

300 -> Value of X i.e. fine

Output :

900  -> total fine collected

Explanation:

Date D=3 means only odd number vehicles with are allowed.

Find will be collected from 2,6 and 8 with an amount of 300 each.

Hence, the output = 900

Constraints:

  • 0<N<=100
  • 1<=a[i]<=9
  • 1<=D <=30
  • 100<=x<=5000

The input format for testing

The candidate has to write the code to accept 4 input(s).

First input – Accept for N(Positive integer) values (a[]), where each value is separated by a new line.

Third input – Accept value for D(Positive integer)

Fourth input – Accept value for X(Positive integer )

The output format for testing

The output should be a positive integer number (Check the output in Example 1, Example e) if no fine is collected then print ”0”.

Solution in C:

#include <stdio.h>
int main() {
    int n;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);
    int d, x;
    scanf("%d %d", &d, &x);
    int countEven = 0, countOdd = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] % 2 == 0)
            countEven++;
        else
            countOdd++;
    }
    if (d % 2 != 0) {
        if (countEven == 0)
            printf("0\n");
        else
            printf("%d\n", countEven * x);
    } else {
        if (countOdd == 0)
            printf("0\n");
        else
            printf("%d\n", countOdd * x);
    }
    return 0;
}

Solution in C++:

#include<bits/stdc++.h> 
using namespace std;

int main() {
    int n;
    cin >> n;
    vector arr(n);
    for (int i = 0; i < n; i++) cin >> arr[i];
    int d, x;
    cin >> d >> x;
    int countEven = 0, countOdd = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] % 2 == 0)
            countEven++;
        else
            countOdd++;
    }
    if (d % 2 != 0) {
        if (countEven == 0)
            cout << "0" << endl;
        else
            cout << countEven * x << endl;
    } else {
        if (countOdd == 0)
            cout << "0" << endl;
        else
            cout << countOdd * x << endl;
    }
    return 0;
}

Solution in Java:

import java.util.*;
class Main
{
   public static void main (String[]args)
   {
       Scanner sc = new Scanner (System.in);
       int n = sc.nextInt ();
       int arr[] = new int[n];
       for (int i = 0; i < n; i++)
           arr[i] = sc.nextInt ();
       int d = sc.nextInt ();
       int x = sc.nextInt ();
       int countEven = 0, countOdd = 0;
       for (int i = 0; i < n; i++)
       {
       if (arr[i] % 2 == 0)
           countEven++;
       else
           countOdd++;
       }
       if (d % 2 != 0)
       {
       if (countEven == 0)
           System.out.println ("0");
       else
           System.out.println (countEven * x);
       }
       else
       {
       if (countOdd == 0)
           System.out.println ("0");
       else
           System.out.println (countOdd * x);
       }
   }
}

Solution in Python:

n = int(input())
arr = list(map(int, input().split()))
d, x = map(int, input().split())
countEven = 0
countOdd = 0
for i in range(n):
    if arr[i] % 2 == 0:
        countEven += 1
    else:
        countOdd += 1
if d % 2 != 0:
    if countEven == 0:
        print("0")
    else:
        print(countEven * x)
else:
    if countOdd == 0:
        print("0")
    else:
        print(countOdd * x)

You can also check- TCS NQT Registration process