# TCS Digital Coding Question

## TCS Digital Programming Questions with Answers 2023

TCS Digital Coding Questions are not like a general Coding Round Questions with Solutions it is all together different from C programming.

Here below you will find similar type programming questions that are asked constantly in TCS Digital test.

Note:- Here you will get updated pattern of TCS Digital coding exam pattern 2022-23. This will help you in preparation of TCS Digital exam. Coding Question For TCS Digital Number of Questions 2 Time Allotted 55 Mins Negative Marking No Cut Off Output is Necessary

## TCS Digital Programming Questions

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 Digital Coding Questions marking Scheme

TCS Digital Recruitment Drive has a Advance Coding round. This round is a bit different from the normal coding round that is asked in TCS. There will be 2 problem statement and each one has total of 2 visible and 3 hidden test cases, instead of total of 5 test cases. Test cases are basically compiler generated input which will check if your output is coming as expected.

Total Time for this section is 55 mins Coding Marks
Marks
Type
0 Test Case
0 Marks
NA
1 Test Case
5 Marks
Shown
2 Test Case
8 Marks
Shown
3 Test Case
12 Marks
Hidden
4 Test Case
18 Marks
Hidden
5 Test Case
22 Marks
Hidden

### Difference between TCS NQT and TCS Digital Coding Round

 TCS NQT TCS Digital 2 problem statement 2 problem statement 2 Qs, 15/30 mins 55 mins basic coding questions advance coding questions(dealing with algorithms and real word problems)

If you are new to programming than you can watch the below video and can start practicing after that, or if you are CS/IT branch student or you know the basics, move to the advance coding questions

## TCS Digital Day 1 Slot 1

### 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]);        }    }}`

## TCS Digital Day 1 Slot 1

### 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 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 4

Problem Statement -: In this even odd problem Given a range [low, high] (both inclusive), select K numbers from the range (a number can be chosen multiple times) such that sum of those K numbers is even.

Calculate the number of all such permutations.

As this number can be large, print it modulo (1e9 +7).

Constraints

• 0 <= low <= high <= 10^9
• K <= 10^6.

Input

• First line contains two space separated integers denoting low and high respectively
• Second line contains a single integer K.

Output

• Print a single integer denoting the number of all such permutations

Time Limit

1

Examples

Example 1

Input

4 5

3

Output

4

Explanation

There are 4 valid permutations viz. {4, 4, 4}, {4, 5, 5}, {5, 4, 5} and {5, 5, 4} which sum up to an even number.

Example 2

Input

1 10

2

Output

50

Explanation

There are 50 valid permutations viz. {1,1}, {1, 3},.. {1, 9} {2,2}, {2, 4},… {2, 10} . . . {10, 2}, {10, 4},… {10, 10}. These 50 permutations, each sum up to an even number.

`#include<bits/stdc++.h>using namespace std;typedef long long int lld;#define mod 1000000007 long e_sum(long m,long n,long K,long N){    if(K==1)    {       return n;    }    else    {        return (N-(m-n)*e_sum(m,n,K-1,N)%(1000000007));    }}int main(){    long low,high,K,m,n,diff,Out,N,i;    scanf("%ld",&low);    scanf("%ld",&high);    scanf("%ld",&K);    diff=high-low+1;    if(diff%2==0)    {        m=diff/2;        n=m;    }    else    {        if(low%2==0)        {            m=(diff-1)/2;            n=m+1;        }        else        {            m=(diff+1)/2;            n=m-1;        }    }    N=m;    for(i=0;i<K-1;i++)    {        N=(N*(m+n))%1000000007;    }    Out=e_sum(m,n,K,N)%1000000007;    printf("%ld",Out);    return 0;}`
`mod=1000000007def esum(m,n,K,N):    if(K==1):       return n    else:        return (N-(m-n)*esum(m,n,K-1,N)%mod) low,high=map(int,input().split())K=int(input())diff=high-low+1if(diff%2==0):    m=diff//2    n=melse:    if(low%2==0):        m=(diff-1)//2        n=m+1    else:        m=(diff+1)//2        n=m-1N=mfor i in range(K-1):    N=(N*(m+n))%modout=esum(m,n,K,N)%modprint(out)`
`import java.util.*;class Solution {    public static int evenSum (int m, int n, int k, int N)     {            if (k == 1)            return n;        else            return (N - (m - n) * evenSum (m, n, k - 1, n) % (1000000007));    }      public static void main (String[]args)     {        Scanner sc = new Scanner (System.in);        int low = sc.nextInt ();        int high = sc.nextInt ();        int k = sc.nextInt ();        int diff = high - low + 1;        int out, n, N, m;            if (diff % 2 == 0)        {            m = diff / 2;            n = m;        }        else        {	                if (low % 2 == 0)    	    {                m = (diff - 1) / 2;                n = m + 1;            }        	else    	    {                m = (diff + 1) / 2;                n = m - 1;            }        }        N = m;        for (int i = 0; i < k - 1; i++)            N = (N * (m + n)) % 1000000007;        out = evenSum (m, n, k, N) % 1000000007;        System.out.println (out);    } }`

### Question 5

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)+")");        }    }}`

### Question 6

Problem Statement:-

Compute the nearest larger number by interchanging its digits updated.Given 2 numbers a and b find the smallest number greater than b by interchanging the digits of a and if not possible print -1.

• Input Format
2 numbers a and b, separated by space.
• Output Format
A single number greater than b.

If not possible, print -1

• Constraints

1 <= a,b <= 10000000

Example 1:

Sample Input:

459 500

Sample Output:
549

Example 2:

Sample Input:

645757 457765

Sample Output:
465577

`#include<bits/stdc++.h>using namespace std; int main(){    string a;    int b,c;    cin>>a>>b;    sort(a.begin(),a.end(),greater<int>());     c=atoi(a.c_str());     if(b>c)    {cout<<-1;    return 0;}    while(b<c)    {        prev_permutation(a.begin(),a.end());        c=atoi(a.c_str());    }    next_permutation(a.begin(),a.end());    cout<<a;}`
`import sysa=input().strip()b=input().strip()a=''.join(sorted(a)[::-1]) if int(a)<=int(b):    print(-1)    sys.exit() else:    if len(a)>len(b):        print(int(a[::-1]))        sys.exit()    else:        n=len(b)        a=list(a[::-1])        s=''        n1=len(a)        for i in range(n):            d=b[i]            j=0            while a[j]<b[i] and n1:                j+=1            if a[j]>b[i]:                s+=a[j]                a.remove(a[j])                a.sort()                s+=''.join(a)                print(int(s))                 sys.exit()            else:                s1=s+a[j]                g=a.copy()                g.remove(a[j])                if n1>1:                     g.sort()                    g=g[::-1]                    s1+=''.join(g)                if int(s1)>int(b):                    s+=a[j]                    a.remove(a[j])                    n1-=1                else:                    while a[j]<=b[i]:                        j+=1                    s+=a[j]                    a.remove(a[j])                    a.sort()                    s+=''.join(a)                    print(int(s))                    sys.exit()print(int(s))`
`import java.util.*;class Solution {      public static TreeSet < Integer > list = new TreeSet <> ();      static void smallestNumber (String str, String ans)     {        if (str.length () == 0)        {            list.add (Integer.parseInt (ans));            return;        }        for (int i = 0; i < str.length (); i++)        {            char ch = str.charAt (i);            String ros = str.substring (0, i) +             str.substring (i + 1);                smallestNumber (ros, ans + ch);        }     }      public static void main (String[]args)     {            Scanner sc = new Scanner (System.in);        int a = sc.nextInt ();        int b = sc.nextInt ();        String s = a + "";        smallestNumber (s, "");            Iterator itr = list.iterator ();            int res = -1;            while (itr.hasNext ())        {            int no = (Integer) itr.next ();            if (no > b)    	    {                res = no;                break;            }        }        System.out.println (res);    }}`

### Question 7

Problem Statement:- In a Conference ,attendees are invited for a dinner after the conference.The Co-ordinator,Sagar arranged around round tables for dinner and want to have an impactful seating experience for the attendees.Before finalizing the seating arrangement,he wants to analyze all the possible arrangements.These are R round tables and N attendees.In case where N is an exact multiple of R,the number of attendees must be exactly N//R,,If N is not an exact multiple of R, then the distribution of attendees must be as equal as possible.Please refer to the example section before for better understanding.
For example, R = 2 and N = 3
All possible seating arrangements are
(1,2) & (3)
(1,3) & (2)
(2,3) & (1)
Attendees are numbered from 1 to N.

Input Format:

• The first line contains T denoting the number of test cases.
• Each test case contains two space separated integers R and N, Where R denotes the number of round tables and N denotes the number of attendees.

Output Format:

Single Integer S denoting the number of possible unique arrangements.

Constraints:

• 0 <= R <= 10(Integer)
• 0 < N <= 20 (Integer)
Sample Input 1:
1
2 5
Sample Output 1:

10

Explanation:

R = 2, N = 5

(1,2,3) & (4,5)

(1,2,4) & (3,5)

(1,2,5) & (3,4)

(1,3,4) & (2,5)

(1,3,5) & (2,4)

(1,4,5) & (2,3)

(2,3,4) & (1,5)

(2,3,5) & (1,4)

(2,4,5) & (1,3)

(3,4,5) & (1,2)

Arrangements like

(1,2,3) & (4,5)

(2,1,3) & (4,5)

(2,3,1) & (4,5) etc.

But as it is a round table,all the above arrangements are same.

`#include<bits/stdc++.h>using namespace std;typedef long long int ll;map <ll,ll> dp;int fac(int n){if(dp[n])return dp[n];dp[n]=n*fac(n-1);return dp[n];} int func(int n){    if(n<=3)        return 1;    return fac(n-1);} int main(){    dp=dp=1;    int tests;cin>>tests;    while(tests--)    {int R,N,c=1;    cin>>R>>N;    if(N<=R)    {        cout<<1;        continue;    }    int a=N/R,n=N%R;     ll ans=fac(N)/(pow(fac(a),R-n) * pow(fac(a+1),n) )/fac(n)/fac(R-n);    for(int i=1;i<=n;i++)        c*=func(a);    for(int i=n+1;i<=R;i++)    c*=func(a-1); cout<<c*ans;}}`
`testcases = int(input())for i in range(testcases):    tables, people = map(int, input().split())    result = 1    if tables >= people:        print(result)    else:        PA = people // tables        PB = PA + 1        TB = people % tables        TA = tables - TB        # Using DP to store factorials pre-hand        fact =         for j in range(1, people + 1):            fact.append(j*fact[j-1])        for i in range(TB):            result = result * (fact[people]//(fact[PB]*fact[people-PB]))            people = people - PB        for i in range(TA):            result = result * (fact[people]//(fact[PA]*fact[people-PA]))            people = people - PA        print(result)`
`import java.util.*;public class Stack{    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        int testcases = scanner.nextInt();        int tables = 0,people;        while (testcases-->0)            tables = scanner.nextInt();            people = scanner.nextInt();            System.out.println(find(tables,people));    }    public static int find(int r,int n)    {        int x = n/r;        int y1 = n%r;        int x1 = 0;        int ans1 = 1;        while(r!=0)        {            if(y1>0)            {                x1 = x+1;                y1 = y1-1;            }            else            {                x1 = x;            }            ans1 = ans1*combination(n,x1);            n = n-x1;            r--;        }        return ans1;    }    public static int factorial(int n)    {        if(n==0||n==1)        {            return 1;        }        return n * factorial(n-1);    }    public static int combination(int n,int r)    {        return factorial(n)/(factorial(n-r)*factorial(r));    }}`

## TCS Digital Coding Round Questions

### TCS Digital Coding Round Questions in Test Pattern and Syllabus

• Number of Questions – 2
• Total time to Solve – 55 mins
• Difficulty Level – Moderate to high Questions
• Cut-off – Run 4 test cases

#### TCS Digital C Command Line Programming Basics

• Keywords like getc, scanf, getch, getchar etc can not be used.
• Instead we use command line arguments to fetch values.

Before reading further for TCS Digital Coding Round Questions, I will suggest not to freak out if you don’t understand in first go. Read everything once and then when you read again things will start to make sense. It is the best resource on the internet to know about TCS  Digital command line Argument Type Questions and TCS Digital C Programming Questions and Answers.

#### TCS Digital C Command Line Programming Basics

• Keywords like getc, scanf, getch, getchar etc can not be used.
• Instead we use command line arguments to fetch values.

Before reading further for TCS Digital Coding Round Questions, I will suggest not to freak out if you don’t understand in first go. Read everything once and then when you read again things will start to make sense. It is the best resource on the internet to know about TCS  Digital command line Argument Type Questions and TCS Digital C Programming Questions and Answers.

#### TCS Digital Programming Test Facts and Questions

TCS  Digital coding test based facts and tricks, TCS Digital Programming Questions, TCS DigitalProgramming Test –

TCS Coding Round TopicsDifficultyTime to solve
LCM HCFMedium20 mins
Swapping and ReversalHard20 mins
Factorial and SeriesMedium20 mins
Operations on NumbersEasy20 mins
MiscMedium – Hard20 mins

### TCS Digital Coding Questions with Answers

Let us consider this, if you wanted to write a basic C program then you would’ve written a main function that would’ve looked like in compiler for TCS Coding Round Questions –

`int Main(){`

// some code

}}

However in command line arguments we write like this –

int main(int argc, char *argv[]){

• argc – It is known as Argument Count and as clear from the name it stores the Count of number of Arguments.
• argv[] – Pointer, contains location of all the values(arguments).
• *argv[] – Array of values of all the arguments.
• They are parameters/arguments supplied to the program when it is invoked.

Thus, now we have two things

1. Total Count of number of Arguments.
2. All the values/pointer location of arguments stored in an array.

Now, you will need one more thing i.e. atoi();

• atoi(); – Converts string into int and atoi(argv[i]); will give the value of argument at ith location in int type format.

Now you can use an int val = atoi(argv[i]); to store the value and then print it with printf(); function.

Check out this video Below to learn how to Solve Command Line Programming. ## Additional Information (FAQ's)

### What is the level of difficulty of the question asked in TCS programming round?

The difficulty level of the TCS Programming round is medium. You should have good command over C/C++ input/output or pattern based programs.

### What languages can we use in TCS  Digital Coding Round Questions?

In TCS Digital Coding Round Questions currently you can  use C/C++ , Java , python + more to code.

### How to clear the TCS Digital coding round?

First you must learn command line programming from our coding dashboard and then try sample questions given on the dashboard to know how to clear the tcs coding round  and TCS Digital C Programming Questions and Answers

## Get over 150+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

## Checkout list of all the video courses in PrepInsta Prime Subscription

### 11 comments on “TCS Digital Coding Question”

• Ankit

Question 4 Solution :-
Scanner sc= new Scanner(System.in);
int n1=sc.nextInt();
int n2=sc.nextInt();
int k=sc.nextInt();

int num=n2-n1+1;
int totalComb= (int)(Math.pow(num, k));

//out of all combinations half will give even sum
int evenSum=(int)Math.ceil(totalComb/2.0);
System.out.print(evenSum); 2
• shounakpurnapatre1

Question 6 Can be get solve with this way with minimum number of lines:
def toString(List):
return ”.join(List)

# a =String , l = Starting index , r = Ending index = n-1.
def permute(a, l, r):
if l == r:
ls.append(toString(a))
else:
for i in range(l, r+1):
a[l], a[i] = a[i], a[l]
permute(a, l+1, r)
a[l], a[i] = a[i], a[l]

x, y = map(int, input().split())
x = str(x)
n = len(x)
a = list(x)
ls = []
permute(a, 0, n-1)

test_list = list(map(int, ls)) # Converting all string into integer
test_list.sort() # Sort the list

for i in range(len(test_list)):
if test_list[i] > y:
print(test_list[i])
break 0
• shounakpurnapatre1

# ************************* UPDATED ******************
# a =String , l = Starting index , r = Ending index = n-1.
def permute(a, l, r, y):
if l == r:

temp2 = ”.join(a)
if int(temp2) > y:
flag = 1
print(temp2)
exit()
else:
for i in range(l, r+1):
a[l], a[i] = a[i], a[l]
permute(a, l+1, r, y)
a[l], a[i] = a[i], a[l]

def getSortedNumber(n):
number = str(n)
number = ”.join(sorted(number))
number = int(number)
return number

x, y = map(int, input().split())
x = getSortedNumber(x)
x = str(x)
n = len(x)
a = list(x)
flag = 0
permute(a, 0, n-1, y)
if flag == 0:
print(-1) 0
• Priyanka

Thank you prepinsta for the questions this type of questions got repeated in the exam.Can you please tell me Where can I prepare for codevita or competitive coding? 1
• avik394451

Solutions are really helpful. But where can I get more practice questions for Codevita and other Hackathons? Can you please guide me? 0
• Shruti

Thankyou PrepInsta. I am highly grateful to you for the questions you provided. I had my test recently and the coding questions were very similar to these. Please help me with the codevita questions too. Where can I find them? 0
• sarina

Thank You so much! These questions really helped me out 0
• Swastik

Question 4
public class Test8 {

public static int fact(int n) {
int fac = 1;
for(int i=1;i<=n;i++) {
fac = fac * i;
}
return fac;
}
public static int comb(int a, int b) {
return fact(a) / (fact(a-b) * fact(b));
}
public static int sum(int a, int b, int c) {
int odd = 0, even = 0,total_outcome,odd_outcome = 0;
for(int i = a;i<=b;i++) {
if(i%2 == 0) {
even++;
}else {
odd++;
}
}
for(int j = 0;j<=c;j++) {
if(j%2!=0) {
odd_outcome = odd_outcome + comb(c,j) * (int)Math.pow(odd, j) * (int)Math.pow(even, c-j);
}
}
total_outcome = (int) Math.pow(odd+even, c);
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = s.nextInt();

System.out.println(sum(a, b, c));
}

} 0
• abhitejkumarvoruganti

import itertools
l,h=map(int,input().split())
k=int(input())
x=range(l,h+1)
perm=[p for p in itertools.product(x, repeat=k)]
cnt=0
for i in list(perm):
if sum(i)%2==0:
cnt+=1
print(cnt) 0
• abhitejkumarvoruganti

# Python3 program for the above approach

# Function to return the number
# of all permutations such that
# sum of K numbers in range is even
def countEvenSum(low, high, k):

# Find total count of even and
# odd number in given range
even_count = high / 2 – (low – 1) / 2
print(even_count,’even_count’)
odd_count = (high + 1) / 2 – low / 2
print(odd_count,’odd_count’)

even_sum = 1
odd_sum = 0

# Iterate loop k times and update
# even_sum & odd_sum using
# previous values
for i in range(0, k):

# Update the prev_even and
# odd_sum
prev_even = even_sum
print(prev_even,’prev_even’)
prev_odd = odd_sum
print(prev_odd,’prev_odd’)

# Even sum
even_sum = ((prev_even * even_count) +
(prev_odd * odd_count))
print(even_sum,’even_sum’)

# Odd sum
odd_sum = ((prev_even * odd_count) +
(prev_odd * even_count))
print(odd_sum,’odd_suma’)

# Return even_sum
print(int(even_sum))

# Driver Code

# Given ranges
low = int(input());
high = int(input());

# Length of permutation
K = int(input());

# Function call
countEvenSum(low, high, K); 0
• Niranjana

Number series with twist-2 Python program solution is wrong. The correct answer should be:

n = int(input(‘enter the number: ‘))

a= 1

b= 1

for i in range(1, n+1):

if(i%2!=0):

a = a*2

else:

b = b*3

if(n%2!=0):

print(‘\n{} term of series is {}\t’.format(n,a/2))

else:

print(‘\n{} term of series is {}\t’.format(n,b/3)) 0