# TCS Ninja Toppers Test Coding Questions

## Latest TCS Ninja Toppers Test Coding Questions 2022

The questions asked in this round will be different from the types of questions asked in TCS Ninja Coding Round and will also be with higher difficulty level.

You will be given 2 coding questions with high difficulty and you will have to solve those in definite time limit of 60 mins.  If you are be able to clear the test then you will get the opportunity to go for TCS Digital Interview.

This test is only for the top 10% performers of TCS NQT (Ninja Profile) candidates.

Click on the button given below to know about the exact syllabus of TCS Ninja Toppers Test. ## Detailed TCS Ninja Toppers Test Syllabus

 TCS Toppers Test Information Total Question 2 Total Alloted 60 min Difficulty High Negative Marking No

## TCS Ninja Toppers Test: Language

#### Languages that you can choose for test –

1. C
2. C#
3. C++
4. Erlang
5. go
7. Java
8. Java 7
9. Kotlin
10. Lua
11. Perl
12. Python
13. Python3
14. Ruby
15. Scala ## TCS Ninja Toppers Test Coding Questions

### Question 1

Problem Description -: Given an array Arr[ ] of N integers and a positive integer K. The task is to cyclically rotate the array clockwise by K.

Note : Keep the first of the array unaltered.

Example 1:

• 5  —Value of N
• {10, 20, 30, 40, 50}  —Element of Arr[ ]
• 2  —–Value of K

Output :

40 50 10 20 30

Example 2:

• 4  —Value of N
• {10, 20, 30, 40}  —Element of Arr[]
• 1  —–Value of K

Output :

40 10 20 30

`#include<bits/stdc++.h>using namespace std;vector<int> rotate(int nums[], int n, int k) {    if (k > n)        k = k % n;    vector<int> ans(n);    for (int i = 0; i < k; i++) {        ans[i] = nums[n - k + i];    }    int index = 0;    for (int i = k; i < n; i++) {        ans[i] = nums[index++];    }    return ans;}int main(){    int Array[] = { 1, 2, 3, 4, 5 };    int N = sizeof(Array) / sizeof(Array);    int K = 2;    vector<int> ans = rotate(Array, N, K);    for (int i = 0; i < N; ++i) {        cout << ans[i] << ' ';    }}`
`import java.util.*;public class Main{    static int[] rotate(int nums[], int n, int k) {        if (k > n)            k = k % n;        int[] ans = new int[n];        for (int i = 0; i < k; i++) {            ans[i] = nums[n - k + i];        }        int index = 0;        for (int i = k; i < n; i++) {            ans[i] = nums[index++];        }        return ans;    }    public static void main(String[] args) {        int Array[] = { 1, 2, 3, 4, 5 };        int N = 5;        int K = 2;        int[] ans = rotate(Array, N, K);        for (int i = 0; i < N; ++i) {            System.out.println(ans[i]);        }    }}`

### Question 2

Problem Description -:  Given two non-negative integers n1 and n2, where n1

For example:

Suppose n1=11 and n2=15.

There is the number 11, which has repeated digits, but 12, 13, 14 and 15 have no repeated digits. So, the output is 4.

Example1:

Input:

• 11 — Vlaue of n1
• 15 — value of n2

Output:

• 4

Example 2:

Input:

• 101 — value of n1
• 200 — value of n2

Output:

• 72
`#include<bits/stdc++.h>using namespace std;int find(int n1, int n2) {    int count = 0;    for (int i = n1 ; i <= n2 ; i++) {        int num = i;        vector<bool> visited;        visited.assign(10, false);        while (num > 0) {            if (visited[num % 10] == true)                break;            visited[num % 10] = true;            num /= 10;        }        if (num == 0)            count++;    }    return count;}int main(){    int n1 = 101, n2 = 200;    cout << find(n1, n2);}`
`import java.util.*;public class Main{    static int find(int n1, int n2) {        int count = 0;        for (int i = n1 ; i <= n2 ; i++) {            int num = i;            boolean[] visited = new boolean;            while (num > 0) {                if (visited[num % 10] == true)                    break;                visited[num % 10] = true;                num /= 10;            }            if (num == 0)                count++;        }        return count;    }    public static void main(String[] args) {        int n1 = 101, n2 = 200;        System.out.println(find(n1, n2));    }}`

Question 3

Problem Statement-:

Identify the logic behind the series

6 28 66 120 190 276….

The numbers in the series should be used to create a Pyramid. The base of the Pyramid will be the widest and will start converging towards the top where there will only be one element. Each successive layer will have one number less than that on the layer below it. The width of the Pyramid is specified by an input parameter N. In other words there will be N numbers on the bottom layer of the pyramid.

The Pyramid construction rules are as follows

1. First number in the series should be at the top of the Pyramid
2. Last N number of the series should be on the bottom-most layer of the Pyramid, with Nthnumber being the right-most number of this layer.
3. Numbers less than 5-digits must be padded with zeroes to maintain the sanctity of a Pyramid when printed. Have a look at the examples below to get a pictorial understanding of what this rule actually means.

Example

If input is 2, output will be

• 00006
• 00028 00066

If input is 3, output will be

• 00006
• 00028 00066
• 00120 00190 00276

Formal input and output specifications are stated below

Input Format:

• First line of input will contain number N that corresponds to the width of the bottom-most layer of the Pyramid

Output Format:

• The Pyramid constructed out of numbers in the series as per stated construction rules

Constraints:

• 0 < N <= 14

`#include<stdio.h>int main (){  int n, a = 0, b = 3, i, re, j;  scanf ("%d", &n);  for (i = 1; i <= n; i++)    {      for (j = 1; j <= i; j++)	{	  a = a + 2;	  if (i == 1)	    b = 3;	  else	    b = b + 4;	  re = a * b;	  printf ("%.5d ", re);	}      printf ("\n");    }  return 0;}`
`import java.util.Scanner;public class LogicPyramid{  public static void main (String[]args)  {    int n, a = 0, b = 3, i, re, j;    Scanner sc = new Scanner (System.in);      n = sc.nextInt ();    for (i = 1; i <= n; i++)      {	for (j = 1; j <= i; j++)	  {	    a = a + 2;	    if (i == 1)	      b = 3;	    else	      b = b + 4;	    re = a * b;	    System.out.println (re);	  }	System.out.println ();      }  }}`
`n=int(input())a,b=0,3for i in range(1,n+1):    for j in range(1,i+1):        a=a+2        if(i==1):b=3        else:b=b+4        re=a*b        print("%.5d"%(re),end=" ")    print()`

Question 4

Problem Statement-:  There are two banks – Bank A and Bank B. Their interest rates vary. You have received offers from both banks in terms of the annual rate of interest, tenure, and variations of the rate of interest over the entire tenure.You have to choose the offer which costs you least interest and reject the other. Do the computation and make a wise choice.

The loan repayment happens at a monthly frequency and Equated Monthly Installment (EMI) is calculated using the formula given below :

EMI = loanAmount * monthlyInterestRate / ( 1 – 1 / (1 + monthlyInterestRate)^(numberOfYears * 12))

Constraints:

• 1 <= P <= 1000000
• 1 <=T <= 50
• 1<= N1 <= 30
• 1<= N2 <= 30

Input Format:

• First line: P principal (Loan Amount)
• Second line: T Total Tenure (in years).
• Third Line: N1 is the number of slabs of interest rates for a given period by Bank A. First slab starts from the first year and the second slab starts from the end of the first slab and so on.
• Next N1 line will contain the period  and their interest rate respectively.
• After N1 lines we will receive N2 viz. the number of slabs offered by the second bank.
• Next N2 lines are the number of slabs of interest rates for a given period by Bank B. The first slab starts from the first year and the second slab starts from the end of the first slab and so on.
• The period and rate will be delimited by single white space.

Output Format: Your decision either Bank A or Bank B.

Explanation:

• Example 1
• Input
• 10000
• 20
• 3
• 5 9.5
• 10 9.6
• 5 8.5
• 3
• 10 6.9
• 5 8.5
• 5 7.9
• Output: Bank B
• Example 2
• Input
• 500000
• 26
• 3
• 13  9.5
• 3  6.9
• 10  5.6
• 3
• 14  8.5
• 6  7.4
• 6  9.6
• Output: Bank A
`#include <stdio.h>#include <math.h>int main (){  double p, s, mi, sum, emi, bank, sq;  int y, n, k, i, yrs, l = 0;  scanf ("%lf", &p);  scanf ("%d", &y);  for (k = 0; k < 2; k++)    {      scanf ("%d", &n);      sum = 0;      for (i = 0; i < n; i++)	{	  scanf ("%d", &yrs);	  scanf ("%lf", &s);	  mi = 0;	  sq = pow ((1 + s), yrs * 12);	  emi = (p * (s)) / (1 - 1 / sq);	  sum = sum + emi;	}      bank[l++] = sum;    }  if (bank < bank)    printf ("Bank A");  else    printf ("Bank B");  return 0;}`
`#include <iostream>#include <math.h>using namespace std;int main (){  double p, s, mi, sum, emi, bank, sq;  int y, n, k, i, yrs, l = 0;  cin >> p;  cin >> y;  for (k = 0; k < 2; k++)    {      cin >> n;      sum = 0;      for (i = 0; i < n; i++)	{	  cin >> yrs;	  cin >> s;	  mi = 0;	  sq = pow ((1 + s), yrs * 12);	  emi = (p * (s)) / (1 - 1 / sq);	  sum = sum + emi;	}      bank[l++] = sum;    }  if (bank < bank)    cout << ("Bank A");  else    cout << ("Bank B");  return 0;}`
`import java.util.Scanner;public class Main{  public static void main (String[]args)  {    Scanner sc = new Scanner (System.in);    double p, s, mi, sum, emi, sq;    int y, n, k, yrs, l = 0;    double[] bank = new double;      System.out.println ("Enter the principal amount");      p = sc.nextDouble ();      System.out.println ("Enter tenature year");      y = sc.nextInt ();    for (k = 0; k < 2; k++)      {	System.out.println ("Enter the no of slabs");	n = sc.nextInt ();	sum = 0;	for (int i = 0; i < n; i++)	  {	    System.out.println ("Enter the period :");	    yrs = sc.nextInt ();	    System.out.println ("Enter the intrest :");	    s = sc.nextDouble ();	    mi = 0;	    sq = Math.pow ((1 + s), yrs * 12);	    emi = (p * (s)) / (1 - 1 / sq);	    sum = sum + emi;	  }	bank[l++] = sum;      }    if (bank < bank)      System.out.println ("Bank A");    else      System.out.println ("Bank B");  }}`
`bank = []principal = int(input())year = int(input())for i in range(0, 2): # 2 Banks    installments = int(input())    sum = 0    for i in range(0, installments):        time, roi = [float(i) for i in input().split()]        square = pow((1+roi), time*12)        emi = (principal*(roi)/(1-1/square))        sum = sum + emi    bank.append(sum)if bank < bank:    print("Bank A")else:    print("Bank B")`

### Question 5

Problem Description -:  In this 3 Palindrome, Given an input string word, split the string into exactly 3 palindromic substrings. Working from left to right, choose the smallest split for the first substring that still allows the remaining word to be split into 2 palindromes.

Similarly, choose the smallest second palindromic substring that leaves a third palindromic substring.

If there is no way to split the word into exactly three palindromic substrings, print “Impossible” (without quotes). Every character of the string needs to be consumed.

Cases not allowed –

• After finding 3 palindromes using above instructions, if any character of the original string remains unconsumed.
• No character may be shared in forming 3 palindromes.

Constraints

• 1 <= the length of input sting <= 1000

Input

• First line contains the input string consisting of characters between [a-z].

Output

• Print 3 substrings one on each line.

Time Limit

1

Examples

Example 1

Input

nayannamantenet

Output

nayan

naman

tenet

Explanation

• The original string can be split into 3 palindromes as mentioned in the output.
• However, if the input was nayanamantenet, then the answer would be “Impossible”.

Example 2

Input

aaaaa

Output

a

a

aaa

Explanation

• The other ways to split the given string into 3 palindromes are as follows –
• [a, aaa, a], [aaa, a, a], [aa, aa, a], etc.
• Since we want to minimize the length of the first palindromic substring using left to right processing, the correct way to split is [a, a, aaa].

Example 3

Input

aaaabaaaa

Output

a

aaabaaa

a

Explanation

• The other ways to split the given string into 3 palindromes are as follows –
• [aaaa, b, aaaa], [aa, aabaa, aa], etc.
• Since we want to minimize the length of the first palindromic substring using left to right processing, the correct way to split is [a, aaabaaa, a].
`#include<bits/stdc++.h>typedef long long int lld;#define mod 1000000007using namespace std;bool pali(string s){    if(s.length()==1) return true;    string s1=s;reverse(s1.begin(),s1.end());    return (s1==s);}int main(){    speed;    string s,s1,s2,s3;    cin>>s;    int l=s.length();    for(int i=1;i<l-1;i++)    {        s1=s.substr(0,i);        if(pali(s1))            for(int j=1;j<l-i;j++)        {            s2=s.substr(i,j);s3=s.substr(i+j,l-i-j);            if(pali(s2)&&pali(s3))            {                cout<<s1<<endl<<s2<<endl<<s3;return 0;            }        }    }    cout<<"Impossible";    return 0;}`
`import sysdef if_palindrome(s):    if len(s)==1:        return True    s1=s[::-1]    return s1==ss=input()l=len(s)for i in range(1,l-1):    s1=s[:i]    if if_palindrome(s1):        for j in range(1,l-i):            s2=s[i:i+j]            s3=s[i+j:]            if if_palindrome(s2) and if_palindrome(s3):                print(s1)                print(s2)                print(s3)                sys.exit()print("Impossible")`
`import java.util.*;class Solution {      public static boolean isPalindrome (String s)     {                if (s.length () == 1)            return true;        StringBuilder sb = new StringBuilder (s);        sb = sb.reverse ();        String rev = new String (sb);        return s.equals (rev);    }      public static void main (String[]args)     {        Scanner sc = new Scanner (System.in);        String str = sc.next ();            int len = str.length ();        String str1 = "", str2 = "", str3 = "";        boolean flag = false;            for (int i = 1; i < len - 1; i++)        {	            str1 = str.substring (0, i);            if (isPalindrome (str1))        	{                for (int j = 1; j < len - i; j++)        	    {		            str2 = str.substring (i, i + j);                    str3 = str.substring (i + j, len);                    if (isPalindrome (str2) && isPalindrome (str3))            		{                        System.out.println (str1 + "\n" + str2 + "\n" + str3);                        flag = true;                        break;                    }                }                if (flag)                    break;            }        }        if (flag == false)            System.out.println ("Impossible");    }}`

### Question 6

Roco is an island near Africa which is very prone to forest fire. Forest fire is such that it destroys the complete forest. Not a single tree is left.This island has been cursed by God , and the curse is that whenever a tree catches fire, it passes the fire to all its adjacent tree in all 8 directions,North, South, East, West, North-East, North-West, South-East, and South-West.And it is given that the fire is spreading every minute in the given manner, i.e every tree is passing fire to its adjacent tree.Suppose that the forest layout is as follows where T denotes tree and W denotes water.

Your task is that given the location of the first tree that catches fire, determine how long would it take for the entire forest to be on fire. You may assume that the lay out of the forest is such that the whole forest will catch fire for sure and that there will be at least one tree in the forest

Input Format:

• First line contains two integers, M, N, space separated, giving the size of the forest in terms of the number of rows and columns respectively.
• The next line contains two integers X,Y, space separated, giving the coordinates of the first tree that catches the fire.
• The next M lines, where ith line containing N characters each of which is either T or W, giving the position of the Tree and Water in the  ith row of the forest.

Output Format:

Single integer indicating the number of minutes taken for the entire forest to catch fire

Constrains:

• 3 ≤ M ≤ 20
• 3 ≤ N ≤ 20

Sample Input 1:

3 3
W T T
T W W
W T T
Sample Output 1:

5

Explanation:
In the second minute,tree at (1,2) catches fire,in the third minute,the tree at (2,1) catches fire,fourth minute tree at (3,2) catches fire and in the fifth minute the last tree at (3,3) catches fire.
Sample Input 2:
6 6
1 6
W T T T T T
T W W W W W
W T T T T T
W W W W W T
T T T T T T
T W W W W W

Sample Output 2:

16

`#include <bits/stdc++.h>using namespace std; char f;int n,m;struct node{int a,b;};bool valid(int x,int y) {return (x>=0&&y>=0&&x<n&&y<m);}bool step(node temp){return (temp.a==-1&&temp.b==-1);}int main(){    cin>>n>>m;    int x,y,i,j,count=0;int ans=1;    cin>>x>>y;x--;y--;    for(i=0;i<n;i++)        for(j=0;j<m;j++)            cin>>f[i][j];    f[x][y]='X';    queue<node>q;   node temp;   temp.a=x;temp.b=y;   q.push(temp);   temp.a=-1;temp.b=-1;   q.push(temp);   while(!q.empty())  {      bool flag=false;      while(!step(q.front()))      {        node count=q.front();        if(valid(count.a+1,count.b)&&f[count.a+1][count.b]=='T')//a+1,b        {            if(flag==false){flag=true;ans++;}            f[count.a+1][count.b]='X';            count.a++;            q.push(count);            count.a--;        }        if(valid(count.a+1,count.b+1)&&f[count.a+1][count.b+1]=='T')//a+1,b+1        {           if(flag==false){flag=true;ans++;}            f[count.a+1][count.b+1]='X';            count.a++;count.b++;            q.push(count);            count.a--;count.b--;        }        if(valid(count.a+1,count.b-1)&&f[count.a+1][count.b-1]=='T')//a+1,b-1        {            if(flag==false){flag=true;ans++;}            f[count.a+1][count.b-1]='X';            count.a++;count.b--;            q.push(count);            count.a--;count.b++;        }        if(valid(count.a,count.b+1)&&f[count.a][count.b+1]=='T')//a,b+1        {            if(flag==false){flag=true;ans++;}            f[count.a][count.b+1]='X';            count.b++;            q.push(count);            count.b--;        }        if(valid(count.a,count.b-1)&&f[count.a][count.b-1]=='T')//a,b-1        {            if(flag==false){flag=true;ans++;}            f[count.a][count.b-1]='X';            count.b--;            q.push(count);            count.b++;        }         if(valid(count.a-1,count.b-1)&&f[count.a-1][count.b-1]=='T')//a-1,b-1        {            if(flag==false){flag=true;ans++;}            f[count.a-1][count.b-1]='X';            count.a--;count.b--;            q.push(count);            count.a++;count.b++;        }         if(valid(count.a-1,count.b+1)&&f[count.a-1][count.b+1]=='T')//a-1,b+1        {            if(flag==false){flag=true;ans++;}            f[count.a-1][count.b+1]='X';            count.a--;count.b++;            q.push(count);            count.a++;count.b--;        }         if(valid(count.a-1,count.b)&&f[count.a-1][count.b]=='T')//a-1,b        {            if(flag==false){flag=true;ans++;}            f[count.a-1][count.b]='X';            count.a--;            q.push(count);            count.a++;        }        q.pop();      }      q.pop();      if(!q.empty())      {          temp.a=-1;          temp.b=-1;          q.push(temp);      }    /*   cout<<endl;   for(i=0;i<n;i++)        {for(j=0;j<m;j++)            {cout<<f[i][j]<<" ";}cout<<endl;}            cout<<endl<<endl;    */  } cout<<ans;}`
`ar=[]n=0br=[(-1,0),(+1,0),(0,+1),(0,-1),(-1,+1),(-1,-1),(+1,+1),(+1,-1)]def bfs(i,j):    key=(i,j)    vis=set()    vis.add(key)    dis=dict()    dis[key]=1     que=[]    que.append((i,j))    time=1    while(que):        x,y=que.pop(0)         for dx,dy in br:            nx,ny=x+dx , y+dy             key=(nx,ny)             if(0<=nx<=n-1 and 0<=ny<=n-1 and key not in vis and ar[nx][ny]=='T'):                vis.add(key)                dis[key]=dis[(x,y)]+1                 que.append((nx,ny))                 time=max(time,dis[key])     return time            n,m=map(int,input().split())r,c=map(int,input().split())ar=[]for i in range(n):    ar.append(tuple(map(str,input().split())))     print(bfs(r-1,c-1))`
`import java.util.HashMap;import java.util.Scanner;class Temp {    static void print(int [][] arr){        for(int i=0;i<arr.length;i++){            for (int j=0;j<arr.length;j++){                System.out.print(arr[i][j]+"\t");            }            System.out.println();        }    }    public static void main (String[] args) {        Scanner scanner = new Scanner(System.in);        int N = scanner.nextInt();        int [][] array = new int[N][N];        HashMap<Integer, Integer> map = new HashMap<>();        int powerpoints = 1 + (N*N)/11;        int counter = 1;        int row = 0, col = 0; // for the current row/col that we are end        int endRow = 0, endColumn = 0; // for the row/col where we need to stop        map.put(0,0);        for(int i=0;i<N/2;i++){            row = col = i;            endColumn = N-i-1;            while (col < endColumn) {                array[row][col] = counter;                if (counter % 11==0)                    map.put(row,col);                counter++;                col++;            }            endRow = N-i-1;            while (row<endRow){                array[row][col] = counter;                if (counter % 11==0)                    map.put(row,col);                counter++;                row++;            }            endColumn = i;            while (col>endColumn){                array[row][col] = counter;                if (counter % 11==0)                    map.put(row,col);                counter++;                col--;            }            endRow = i;            while (row>endRow){                array[row][col] = counter;                if (counter % 11==0)                    map.put(row,col);                counter++;                row--;            }        }        if (N%2==1)            array[N/2][N/2] = N*N;        print(array);        System.out.println("Total Power Points: " + powerpoints);        for (Integer key: map.keySet()) {            System.out.println("("+key+ ","+map.get(key)+")");        }    }}`

## FAQs

#### What will be the difficulty level of Toppers test?

The difficulty level of Toppers Test is high. The difficulty level will be as same of TCS Digital and TCS Digital is considered as the most tough exam held by TCS.

#### Will there be negative marking in the exam?

As per the current information, No there will be no negative marking in the exam. But yes, the difficulty level will be high so you need to prepare well for this round.