TCS Coding Questions 2022 Day 1 Slot 2
Coding Question 1 for 2022 (September slot)
In this article, we will discuss about the TCS Coding Question which is asked in the TCS placement test. This type of Coding Questions will help you to crack your upcoming TCS exam as well as during your inteview process.
TCS Coding Question Day 1 Slot 2 – Question 1
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 :
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.
#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; }
#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 Solution { 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]+” “); } }
n = int(input()) arr = [] for i in range(n): arr.append(int(input())) for i in sorted(arr): print(i, end=" ")
Login/Signup to comment