TCS Digital Advanced Coding Questions and Answers 2023
Advanced Coding Questions and Answers
TCS Digital is an advanced opportunity offered to the students by TCS. This is a much better position than TCS Ninja, in terms of salary and working experience.
For getting qualified for this post you have to clear TCS Digital Advance Coding Section, which is an additional section after TCS NQT Exam for getting qualified for the Digital profile.
Advanced Coding Details
Topics | No of Questions |
---|---|
Number of Questions | 2 |
Time Limit | 55 mins |
Difficulty level | high |
Package Offered |
|
TCS Digital has almost the same syllabus as TCS CodeVita Coding Competition, even the last year TCS Digital Coding Round was held on CodeVita compiler, even this year there are very high speculation that the coding round again will be held on CodeVita only, so we recommend you that while preparing for TCS Digital make sure that you overlook TCS CodeVita Coding Questions.
Lets Prepare
Question 1
You are given an array A of size N. Your friend gave me an amazıng task for you. Your friend likes one type of Sequence. So, he called that type of sequence a fair sequence. You should select a fair sequence of maximum length from an array. Here a fair sequence is nothing but you have to select elements in a pattern like positive element, negative element, positive element… (negative element, positive element, negative element, to form a sequence.
Your task is to print the maximum sum of elements possible by selecting a fair subsequence with maximum length.
Ex: If array A = [21, 12, 13, -21, -2]. Here your minimum length can be which subsequences 21, -2. The sum is 19. Your task is to print the maximum sum of elements possible by selecting a fair subsequence with maximum length.
NOTE: You should select the elements in a fair sequence only.
Example – 1:
- Input:
5 – N ( Number of elements in an array )
21 12 13 -21 -2 – Array A consists of N elements - Output:
19 - Explanation:
Here you can select 21, -2 subsequences of maximum length 2. The sum is 19 which is the maximum possible for a fair subsequence of length 2.
def fun(arr, n): ans = [] t = 1 if arr[0] > 0: t = 0 i = 0 while i < n: if t == 0: j = i while j < n: if arr[j] > 0: j += 1 else: break ans.append(max(arr[i:j])) i = j t = 1 else: j = i while j < n: if arr[j] < 0: j += 1 else: break ans.append(max(arr[i:j])) i = j t = 0 return sum(ans) n = int(input()) ar = list(map(int, input().split())) print(fun(ar, n))
Question 2
Alice has introduced a new online game which has N levels i e., 1 to N. She wants to get reviews for each level of this game so she will launch only a single level of game on any particular day, and on that day users of this game are allowed to play only that particular level. As there are N levels so it will take exactly N days to launch all levels of the game, it is not necessary that level of game will be launched in increasing order, she will pick any random level on particular day and launch it, and it is obvious that any level of the game can’t be launched twice. After completing the level, the user will give reviews and she will give them one reward unit for each level the user will complete. Alice has put one constraint on users that only after completing any level of game, user will be able to play higher levels. For E.g. If Alice has launched the 3rd level of the game on the first day and if any user completes it then he will get one reward point, but now. he can’t play the game with level 1 and level 2.
NOTE: If a user wants to skip to play on any number of days, he is free to do that.
You are the best gamer, so you can easily complete all levels. As you want to maximize your reward points, you want to play as many levels as you can. Alice has already announced the order in which she will launch levels of his game, your aim is to maximize your reward points.
Given number of levels of games(N) and order of level of games launched one by one on each day. You have to output maximum reward points you can earn.
Hint: You will play any game if and only if that number is becoming the part of the longest subsequence in array of order of games.
Example 1:
- Input:
5 -> N = 5
2 1 3 4 5 -> Order of levels, Alice will launch one by one - Output:
4 - Explanation:
If Alice plays the 2nd level of the game on the first day, then he will not be able to play the 1st level of the game on the 2nd day. As after completing the 2nd level, he will be able to play higher levels. From 3rd day he can play all upcoming levels as those levels are in increasing order. So, possible sequences of levels of games played to maximize rewards points are [2, 3, 4, 5] or [1, 3, 4, 5]. In both cases he will get 4 reward points.
Example 2:
- Input:
5 -> N = 5
5 4 3 2 1 -> Order of levels, Alice will launch one by one - Output:
1 - Explanation:
Alice has launched levels in decreasing order, so he will be able to play exactly one level of game. After playing any level, there are no higher levels on coming days, so maximum reward point is 1.
def fun(n, arr): if arr == sorted(arr, reverse=True): return 1 if arr == sorted(arr): return n ans = 1 for i in range(n - 1): m = 1 for j in range(i + 1, n): if arr[j] > arr[i]: m += 1 ans = max(m, ans) return ans N = int(input()) ar = list(map(int, input().split())) print(fun(N, ar))
Question 3
King Jeremy’s family has ruled a kingdom for N consecutive years numbered from 1 to N. The year i is described by a prosperity value A[i]. This is a positive integer when there was prosperity in the year and a negative integer when it was a difficult year for the kingdom. A historical period is described with two integers, S and F as [S, F], i.e. [Start, Finish], where S and F are from 1 to N, S <= F.
The target is to pick 2 historical periods, with the following 6 conditions:
- The two periods shouldn’t have common years. For example (1,5) has no common year with [6,7).
- the First period should start earlier than the second one, 1.e. (1,5) should be the first period, and then the [6,7] should start.
- There should be a difference of more than K integers between the Finish of the first period and the start of the 2nd period.
- Sum of prosperity values for the years in the periods chosen should be as large as possible.
Given N, A[ ], and K, give this maximum prosperity value as output.
E.g.
N = 5, number of years
K = 3, difference between 2 periods.
A = {-1, 1, 2, 3, -1} prosperity value for each year.
There is only 1 way to choose the two periods, which is [1,1] and [5,5) as the difference has to be greater than 3 (value of K).
The prosperity values for these are
[1, 1] = -1
[5, 5] = -1
The Some of these values are -2. Hence, the answer is -2.
Example 1:
- Input:
8 -> Input Integer, N
3 -> Input Integer, K
{5, 5, -1, -2, 3, -1, 2, -2} -> Input sequence, A[ ]. - Output:
12 -> Output - Explanation:
In the above case: N equals to 8, K equals to 3, Al equals to {5, 5,-1,-2,3,-1, 2, -2}. It is optimal to choose [1, 2] and [7, 7) periods. That is the only optimal choice that you can make.
So the values will be
[1, 2] = 5 5
[7, 7] = 2
The sum of it will be 5 + 5 + 2 = 12
Example 2:
- Input:
6 -> Input Integer, N
0 -> input Integer, K
{5, -1, 5, 0, -1, 9} -> Input sequence A[ ]. - Output:
18 -> Output - Explanation:
In the above case: N equals 6, and K equals to 0. All equals to {5,-1,5, 0, 1,9}. It is optimal to choose [1, 3] and [6, 6] periods. But that is not the only optimal choice that you can make So the values will be
[1, 3] = 5 – 1 5
[6, 6] = 9
The sum of it will be 5 -1+5+9 = 18.
n = int(input()) k = int(input()) A = list(map(int, input().split())) final = [] for i in range(1, n + 1): for j in range(1, n + 1): if j >= i: final.append([i, j]) maximum = 0 for i in range(len(final)): for j in range(len(final)): if i != j: a = [i for i in range(final[i][0], final[i][1] + 1)] b = [i for i in range(final[j][0], final[j][1] + 1)] if len(set(a).intersection(set(b))) == 0: if final[i][1] < final[j][0]: ans = final[j][0] - final[i][1] if ans > k: sumvalue = 0 for p in range(((final[i][0]) - 1), final[i][1]): sumvalue += A[p] for p in range(((final[j][0]) - 1), final[j][1]): sumvalue += A[p] maximum = max(maximum, sumvalue) print(maximum)
Question 4
Radha is attending her sister’s wedding, and there are a lot of things to do including packing and food and decorating. Radha took up the responsibility for packing the sweets, as no one was interested in doing such tedious work. She got an idea, where she announced that we will pick a winner from a packing contest, and those who win this game will be given a surprise gift. The best part is that more than 1 person can be the winner in this game.
Radha, by default, is the first player. So, the game goes like this:
- All the sweet boxes are represented with numbers, to differentiate them from each other. Let us say that a box numbered ‘1’ will contain a different sweet compared to the one which is numbered ‘2’.
- Each player will be given different/same combinations of sweets boxes in different/same quantities.
- Each player has to pack all the respective boxes given to them, in one final package.
- As a default point, each person will be given the number of points equal to the number of boxes they pack. Let us say they have 6 sweet boxes in their queue, they will get 6 points as default.
- If the final package contains 4 different types of sweets, then they will get an additional 1 point.
- If the final package contains 5 different types of sweets, then they will get additional 2 points.
- If the final package contains 6 or more different types of sweets, then they will get additional 4 points.
Radha is Player 1, and the remaining players follow after that. The input will be in the format given below:
For Player-1 (Radha):
1
6 1 2 3 4 5 7
This means there is only 1 player, and 6 is the number of boxes given to her. And the remaining values (1 2 3 4 5 7).
If we have multiple participants then, say we have 3 participants
3
6 1 2 3 4 5
4 1 3 2 2
5 1 2 2 3 3
This means we have 3 participants (N=3)
First participant:
- Number of boxes 6, N = Z[0]
- The types of sweets in these 6 boxes are, respectively, as 1 2 3 4 5 7, 1.e., Z[1, N]
Second participant:
- Number of boxes 4, N = Z[0]
- The types of sweets in these 6 boxes are, respectively, as 1 3 2 2, i.e., Z[1, N]
Third participant:
- Number of boxes 5, N = Z[0]
- The types of sweets in these 6 boxes are respectively, as 1 2 2 3 3 i.e., Z[1, N]
Your output will be:
Radha: If Radha wins.
Tie: If 2 or more 2 players have the same score.
A[i]: Index of the player.
Example 1:
- Input:
2 -> Input string. Integer N.
6 1 2 3 4 5 6-> Input Integer, Z[ ]
9 3 3 3 4 4 4 5 5 5 -> Input integer, Z[ ] - Output:
Radha -> Output - Explanation:
From the above inputs let’s calculate the total points for each player.
Player 1: Radha
Has 6 boxes, so 6 points in the beginning.
She has 6 different types of sweets (from 1-6), hence 6 more points to that.
Total of 6 + 6 = 12 points
Player 2:
Has 9 boxes, so 9 points in the beginning.
She has only 3 different types of sweets (3,4 & 5), so no points to that.
Total of 9 points.
Radha is a winner with more points.
Example 2:
- Input:
2 -> Input string. Integer N.
3 1 2 3 -> Input Integer, A[ ], Z[ ].
4 1 2 3 4 -> Input integer, A[ ], Z[ ]. - Output:
2 -> Output - Explanation:
From the above inputs let’s calculate the total points for each player:
Player 1: Radha
Has 3 boxes, so 3 points in the beginning.
She has 3 different types of sweets (from 1-3), so no points to that.
Total of 3 points.
Player 2:
Has 4 boxes, so 4 points in the beginning.
She has only 3 different types of sweets (1 – 4), so 1 point to that.
Total of 3+1 = 4 points.
Player 2 is a winner with more points. So, the answer is 2.
def find(l1): length = len(l1) finalans = l1[0] l1.pop(0) setl1 = set(l1) if len(setl1) == 6: finalans += 4 elif len(setl1) == 4: finalans += 1 elif len(setl1) == 5: finalans += 2 finalans += sum(setl1) return finalans n = int(input()) final = [] for i in range(n): l1 = list(map(int, input().split())) finalSum = find(l1) final.append(finalSum) maximum = max(final) countofMax = final.count(maximum) if countofMax == 1: if final[0] == maximum: print("Radha") else: print(final.index(maximum)) else: for i in final: if i == maximum: print(i + 2, end=" ")
Question 5
Reddington has invested his money in stock of N companies, but lately, he realized that he has invested money in a very random manner. He wants to restructure the money he invested. He decided on an integer K which he will use to modify the amount invested either by putting k more amount for a particular company or withdrawing the same K amount. He will withdraw from one company by selling a stock) and will invest the same amount of K in another company (by buying stock). For more than one transaction (either buy or sell) of stock in the same company have some charges per month, such that he will not do more than one transaction of a particular company means either he will buy or sell the stock of amount K for a company or he will not do any transaction for that company. But he can do as many transactions as he wants to be provided that in one company he will do only one transaction. As you are his best friend so he reached out to you o for help.
Reddington wants to keep the difference between the smallest and largest invested amount minimal, can you please help him to get this minimum difference?
NOTE: Reddington can sell the stock of K from a particular company only if the invested amount value for that particular company is higher than k.
Hint: To keep the difference minimum, if any transaction is needed then he needs to sell the stock of amount from the company with the highest invested amount and invest the same in the company with the smallest invested amount
Example 1:
- Input:
2100 > N=100, K=100
100 1000 -> Invested amount for each company - Output:
700 - Explanation:
Two companies C1 and C2 have invested amounts of 100 and 1000. From the company, C2 Reddington will sell the stock of 100(K) units and buy the stock of company C2. So, now the invested amount will be 200 and 900, and now Reddington can’t do more transactions, so the minimum difference will be 900-200 = 700.
Example 2:
- Input:
5 100 -> N=5, K=100
100 200 300 400 500 -> Invested amount for each - Output:
200 - Explanation:
Five companies C1, C2, C3, C4, and C4 having invested amounts as 100, 200, 300, and 400,500 Reddington will sell the stock of C5 of 100 units and put it in C1. So, the invested amount will be 200, 200, 300, 400, 400, Now Reddington will sell the stock of C4 and put it in C2, then the invested amount will be 200, 300, 300, 300,02 400. Reddington can’t do more transactions now, so the minimum difference will be 400 – 200 = 200.
def fun(n, k, arr): c = (max(arr) + min(arr)) // 2 for i in range(n): if arr[i] < c: arr[i] += k elif arr[i] > c: arr[i] -= k return max(arr) - min(arr) N, K = map(int, input().split()) ar = list(map(int, input().split())) print(fun(N, K, ar))
Question 6
Vijay, an industrialist, recently opened a fuel industry. There are N numbers of different categories of fuel and each fuel is stored in a fixed site container. The size of the container can vary from fuel to fuel. Hari, a fuel merchant, visited Vijay’s industry and he wanted to purchase fuels for his shop. Hari has a limited amount of money (K) and wants to buy fuel. Hari will not buy more than one container of any fuel category. Hari wants to maximize the overall volume i.e., the sum of the volume of fuels he buys. Your task is to get the maximum overall volume of fuels that Hari can purchase.
Given the number of categories of fuels (N), money units (K) price of a container of each category of fuel, and volume contained in a container for each category.
NOTE: Quantity (volume) of container will be given in the same order as the volume of price.
Hint: Break problems into parts and get the overall volume for smaller N and smaller K.
Example 1:
- Input:
5, 105 -> N = 5, K=105
10 10 40 50 90 -> prices of the container of each fuel category.
10 20 20 50 150 -> volume of container of each fuel Category. - Output:
170 - Explanation:
There are 5 fuel categories and Hani has 105 units of $ money. To have maximum fuel volume Hari can buy oil in 2nd and 5th positions. Total cost= 10 + 90 = 100 and it is less than 105(money which Hari has). Total volume = 20 + 150 = 170. It’s the max volume Hari can get; no other combination can get more volume than this.
Example 2:
- Input:
5 100 -> N = 5, K=100
10 20 30 40 100 -> prices of a container of each fuel category.
10 20 30 40 100 -> volume of container of each fuel - Output:
100 - Explanation:
Hari can buy either 1st four categories or only 5th category of fuel. In either case, the total amount will be 100 and the volume will be 100 (which is the maximum volume possible).
def getMaxVol(money, price, volume, n): K = [] for i in range(n + 1): temp = [] for j in range(money + 1): temp.append(0) K.append(temp) for i in range(n + 1): for m in range(money + 1): if i == 0 or m == 0: K[i][m] = 0 elif price[i - 1] <= m: K[i][m] = max(volume[i - 1] + K[i - 1][m - price[i - 1]], K[i - 1][m]) else: K[i][m] = K[i - 1][m] return K[n][money] N, money = map(int, input().split()) price = list(map(int, input().split())) volume = list(map(int, input().split())) print(getMaxVol(money, price, volume, len(volume)))
Question 7
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
- First number in the series should be at the top of the Pyramid
- 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.
- 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 Main { 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,3 for 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 8
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[5], 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[0] < bank[1]) 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[5], 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[0] < bank[1]) cout << ("Bank A"); else cout << ("Bank B"); return 0; }
Question 9
Problem Statement-:One person hands over the list of digits to Mr. String, But Mr. String understands only strings. Within strings also he understands only vowels. Mr. String needs your help to find the total number of pairs that add up to a certain digit D.
The rules to calculate digit D are as follows
- Take all digits and convert them into their textual representation
- Next, sum up the number of vowels i.e. {a, e, i, o, u} from all textual representation
- This sum is digit D
Now, once digit D is known find out all unordered pairs of numbers in input whose sum is equal to D. Refer example section for better understanding.
Constraints
- 1 <= N <= 100
- 1 <= value of each element in second line of input <= 100
Number 100, if and when it appears in the input should be converted to textual representation as a hundred and not as one hundred. Hence the number of vowels in the number 100 should be 2 and not 4
Input
- the First line contains an integer N which represents the number of elements to be processed as input
- the Second line contains N numbers separated by space
Output
- Lower case representation of a textual representation of the number of pairs in input that sum up to digit D
Note: – (If the count exceeds 100 print “greater 100”)
Time Limit
1
Examples
Example 1
Input
5
1 2 3 4 5
Output
one
Explanation
1 -> one -> o, e
2 -> two -> o
3 -> three -> e, e
4 -> four -> o, u
5 -> five – > i, e
Thus, count of vowels in textual representation of numbers in input = {2 + 1 + 2 + 2 + 2} = 9. Number 9 is the digit D referred to in the section above.
Now from the given list of numbers {1,2,3,4,5} -> find all pairs that sum up to 9.
Upon processing this we know that only a single unordered pair {4, 5} sum up to 9. Hence the answer is 1. However, output specification requires you to print textual representation of number 1 which is one. Hence the output is one.
Note: – Pairs {4, 5} or {5, 4} both sum up to 9. But since we are asking to count only unordered pairs, the number of unordered pairs in this combination is only one.
Example 2
Input
3
7 4 2
Output
zero
Explanation
7 -> seven -> e, e
4 -> four -> o, u
2 -> two -> o
Thus, count of vowels in textual representation of numbers in input = {2 + 2 + 1} = 5. Number 5 is the digit D referred to in the section above.
Since no pairs add up to 5, the answer is 0. The textual representation of 0 is zero. Hence the output is zero.
#include<bits/stdc++.h> using namespace std; vector <string>k(101,""); int vowel(string s) { int sum=0; for(auto i:s) if(i=='a'||i=='e'||i=='i'||i=='o'||i=='u') sum++; return sum; } string findWord(int a) { if(k[a]!="") return k[a]; if(a<20&&a>15) return k[a]=k[a%10]+"teen"; if(a%10==0) return k[a]=k[(a/10)]+"ty"; return k[a]=k[(a/10)*10]+"-"+k[a%10]; } int main() { k[0]="zero";k[1]="one";k[2]="two";k[3]="three";k[4]="four";k[5]="five"; k[6]="six";k[7]="seven";k[8]="eight";k[9]="nine"; k[10]="ten";k[11]="eleven"; k[12]="twelve";k[13]="thirteen";k[14]="fourteen";k[15]="fifteen"; k[20]="twenty";k[30]="thirty";k[40]="forty";k[50]="fifty"; k[80]="eighty";k[100]="hundred"; //for(int i=0;i<101;i++)cout<<i<<" "<<findWord(i)<<endl; int n,sum1=0,sum2=0; cin>>n; vector <int> a(n); for(int i=0; i<n; i++) { cin>>a[i]; sum1+=vowel(findWord(a[i])); } for(int i=0; i<n-1;i++){ for(int j=i+1; j<n;j++) { if(a[i]+a[j]==sum1) sum2++; } } cout<<findWord(sum2); }
k = [''] * 101 k[0] = "zero" k[1] = "one" k[2] = "two" k[3] = "three" k[4] = "four" k[5] = "five" k[6] = "six" k[7] = "seven" k[8] = "eight" k[9] = "nine" k[10] = "ten" k[11] = "eleven" k[12] = "twelve" k[13] = "thirteen" k[14] = "fourteen" k[15] = "fifteen" k[20] = "twenty" k[30] = "thirty" k[40] = "forty" k[50] = "fifty" k[80] = "eighty" k[100] = "hundred" def vowel(str): s = 0 for i in str: if i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u': s += 1 return s def findword(a): if k[a] != "": return k[a] elif 20 > a > 15: k[a] = k[a % 10] + "teen" return k[a] elif a > 100: print("Wrong Input") return 0 else: k[a] = k[(a // 10) * 10] + "-" + k[a % 10] return k[a] sum1 = 0 sum2 = 0 n = int(input()) a = list(map(int, input().split())) for i in range(n): sum1 += vowel(findword(a[i])) for i in range(n - 1): for j in range(i + 1, n): if a[i] + a[j] == sum1: sum2 += 1 print(findword(sum2))
import java.util.*; class Main { static String arr[] = new String[101]; public static int vowel (String str) { int sum = 0; for (int i = 0; i < str.length (); i++) if (str.charAt (i) == 'a' || str.charAt (i) == 'e'|| str.charAt (i) == 'i' || str.charAt (i) == 'o'|| str.charAt (i) == 'u') sum += 1; return sum; } public static String findWord (int no) { if (no <= 15) return arr[no]; if (no < 20 && no > 15) { arr[no] = arr[no % 10] + "teen"; return arr[no]; } if (no % 10 == 0) { arr[no] = arr[no / 10] + "ty"; return arr[no]; } if (no > 100) return "greater 100"; arr[no] = arr[(no / 10) * 10] + "-" + arr[no % 10]; return arr[no]; } public static void main (String[]args) { for (int i = 0; i < 100; i++) arr[i] = ""; arr[0] = "zero"; arr[1] = "one"; arr[2] = "two"; arr[3] = "three"; arr[4] = "four"; arr[5] = "five"; arr[6] = "six"; arr[7] = "seven"; arr[8] = "eight"; arr[9] = "nine"; arr[10] = "ten"; arr[11] = "eleven"; arr[12] = "twelve"; arr[13] = "thirteen"; arr[14] = "fourteen"; arr[15] = "fifteen"; arr[20] = "twenty"; arr[30] = "thirty"; arr[40] = "forty"; arr[50] = "fifty"; arr[60] = "sixty"; arr[70] = "seventy"; arr[80] = "eighty"; arr[90] = "ninenty"; arr[100] = "hundred"; int sum1 = 0; int sum2 = 0; Scanner sc = new Scanner (System.in); int n = sc.nextInt (); int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt (); for (int i = 0; i < n; i++) sum1 += vowel (findWord (a[i])); for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == sum1) sum2 += 1; System.out.println (findWord (sum2)); } }
Question 10
Problem Statement:- Jaya invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of Programmer (the 256thday of the year) during a year in the inclusive range from 1700 to 2700. From 1700 to 1917 , Russia’s official calendar was the Julian Calendar since 1919 they used the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918 , when the next day after 31 January was February 14 . This means that in 1918, February 14 was the 32nd day of the year in Russia. In both calendar systems, February is the only month with a variable amount of days; it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4 ; in the Gregorian calendar, leap years are either of the following:
- Divisible by 400
- Divisible by 4 and not divisible by 100
Given a year, y, find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.
For example, the given year is 1984.1984 is divisible by 4, so it is a leap year. The 256 day of a leap year after 1918 is September 12, so the answer is 12.9.1984.
Function Description
- Complete the programmerday function in the editor below. It should return a string representing the date of the 256th day of the year given.
- programmerday has the following parameter(s):
- year: an integer
Input Format
- A single integer denoting year y.
Output Format
- Print the full date of programmerday during year y in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.
Sample Input
2017
Sample Output
13.09.2017
#include <stdio.h> int main() { int year; scanf("%d",&year); if(year>=1700 && year<=1917) { if(year%4==0) { printf("12.09.%d",year); } else { printf("13.09.%d",year); } } else if(year==1918) { printf("26.09.%d",year); } else { if((year%400==0)||((year%4==0)&&(year%100!=0))) { printf("12.09.%d",year); } else { printf("13.09.%d",year); } } return 0; }
#include <iostream> #include <math.h> using namespace std; int main() { int n; cin>>n; if(n==1918) cout<<"26.09.1918"; else if(n==1700 || n==1800 || n==1900) cout<<"12.09."<<n; else if(n%400==0) cout<<"12.09."<<n; else if(n%4==0) { if(n%100==0) cout<<"13.09."<<n; else cout<<"12.09."<<n; } else cout<<"13.09."<<n;; return 0; }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int year = sc.nextInt(); if(year>=1700 && year<=1917){ if(year%4==0){ System.out.println("12.09."+year); } else{ System.out.println("13.09."+year); } } else if(year==1918){ System.out.println("26.09."+year); } else{ if(( year%400 == 0) | (( year%4 == 0 ) && ( year%100 != 0))){ System.out.println("12.09."+year); } else{ System.out.println("13.09."+year); } } } }
def dayOfProgrammer(year): if year>=1700 and year<=1917: if year%4==0: return "12.09."+str(year) else: return "13.09."+str(year) elif year==1918: return "26.09."+str(year) else: a=not(year%100) if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))): return "12.09."+str(year) else: return "13.09."+str(year) year = int(input().strip()) result = dayOfProgrammer(year) print(result)
Question 11
Problem Statement:- Hobo’s Drawing teacher asks his class to open their books to a page number. Hobo can either start turning pages from the front of the book or from the back of the book. He always turns pages one at a time. When she opens the book, page 1 is always on the right side: When he flips page 1, he sees pages 2 and 3. Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is n pages long, and he wants to turn to page p, what is the minimum number of pages he will turn? He can start at the beginning or the end of the book. Given n and p, find and print the minimum number of pages Hobo must turn in order to arrive at page p
Function Description
Complete the countpage function in the editor below. It should return the minimum number of pages Hobo must turn.
countpage has the following parameter(s):
- n: the number of pages in the book
- p: the page number to turn to
Input Format
- The first line contains an integer n, the number of pages in the book.
- The second line contains an integer, p, the page that Hobo’s teacher wants her to turn to.
Output Format
- Print an integer denoting the minimum number of pages Hobo must turn to get to page p
Sample Input
6
2
Sample Output
1
#include<stdio.h> int main() { int n, p, min; scanf("%d",&n); scanf("%d",&p); min = (n/2)-(p/2); if(min>p/2) { min = p/2; } printf("%d",min); return 0; }
#include <iostream> using namespace std; int main() { int n=0,p=0,min; cin >> n; cin >> p; min=(n/2)-(p/2); if(min>p/2) min=p/2; cout << min; return 0; }
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int p = sc.nextInt();
System.out.println(Math.min(p/2, n/2 - p/2));
}
}
def pageCount(n, p): return min(p//2, n//2 - p//2) n = int(input()) p = int(input()) result = pageCount(n, p) print(result)
Question 12
Problem Statement:- Dr. Vishnu is opening a new world class hospital in a small town designed to be the first preference of the patients in the city. Hospital has N rooms of two types – with TV and without TV, with daily rates of R1 and R2 respectively.
However, from his experience Dr. Vishnu knows that the number of patients is not constant throughout the year, instead it follows a pattern. The number of patients on any given day of the year is given by the following formula –
- (6-M)^2 + |D-15| ,
where M is the number of month (1 for jan, 2 for feb …12 for dec) and D is the date (1,2…31).
All patients prefer without TV rooms as they are cheaper, but will opt for with TV rooms only if without TV rooms are not available. Hospital has a revenue target for the first year of operation. Given this target and the values of N, R1 and R2 you need to identify the number of TVs the hospital should buy so that it meets the revenue target. Assume the Hospital opens on 1st Jan and year is a non-leap year.
Constraints
Hospital opens on 1st Jan in an ordinary year
- 5 <= Number of rooms <= 100
- 500 <= Room Rates <= 5000
- 0 <= Target revenue < 90000000
Input Format
- First line provides an integer N that denotes the number of rooms in the hospital
- Second line provides two space-delimited integers that denote the rates of rooms with TV (R1) and without TV (R2) respectively
- Third line provides the revenue target
Output
- Minimum number of TVs the hospital needs to buy to meet its revenue target. If it cannot achieve its target, print the total number of rooms in the hospital.
Test Case
Example-1 :
Input
20
1500 1000
7000000
Output
14
Explanation
Using the formula, the number of patients on 1st Jan will be 39, on 2nd Jan will be 38 and so on. Considering there are only twenty rooms and rates of both type of rooms are 1500 and 1000 respectively, we will need 14 TV sets to get revenue of 7119500. With 13 TV sets Total revenue will be less than 7000000
Example-2 :
Input
10
1000 1500
10000000
Output
10
Explanation
In the above example, the target will not be achieved, even by equipping all the rooms with TV. Hence, the answer is 10 i.e. total number of rooms in the hospital.
#include<bits/stdc++.h> using namespace std; int R2,R1,N; int M[]={0,25,16,9,4,1,0,1,4,9,16,25,36}; int D[]={0,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int MM[]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int func(int p) {int s,sum=0; for(int m=1;m<=12;m++) for(int d=1;d<=MM[m];d++) {s=min(M[m]+D[d],N); sum+=min(p,s)*R2 + (s-min(p,s))*R1; } return sum; } int main() { int R,l=0; cin>>N>>R1>>R2>>R; int nn=N; while(nn--) { if(func(nn)>=R) {l=nn;break; } } cout<<N-l; }
import java.util.*; class Main { static int R1, R2, N; static int M[] = { 0, 25, 16, 9, 4, 1, 0, 1, 4, 9, 16, 25, 36 }; static int D[] ={ 0, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; static int MM[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static int func (int p) { int s, sum = 0; for (int m = 1; m <= 12; m++) { for (int d = 1; d <= MM[m]; d++) { s = (int) Math.min (M[m] + D[d], N); sum +=(int) Math.min (p, s) * R2 + (s - (int) Math.min (p, s)) * R1; } } return sum; } public static void main (String[]args) { Scanner sc = new Scanner (System.in); int R, l = 0; N = sc.nextInt (); R1 = sc.nextInt (); R2 = sc.nextInt (); R = sc.nextInt (); int nn = N; while (nn-- != 0) { if (func (nn) >= R) { l = nn; break; } } System.out.println (N - l); } }
M=[0,25,16,9,4,1,0,1,4,9,16,25,36] D=[0,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] MM=[0,31,28,31,30,31,30,31,31,30,31,30,31] N=int(input()) R1,R2=map(int,input().split()) R=int(input()) nn,L=N,0 while(nn): sum=0 for m in range(1,13): for d in range(1,MM[m]+1): s=min(M[m]+D[d],N) sum+=min(nn,s)*R2 + (s-min(nn,s))*R1 if(sum>=R): L=nn break nn-=1 print(N-L)
Question 13
Problem Statement:- You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value.
For example, given an array of [1, 2, 3, 4] and a target value of 1, we have three values meeting the condition: 2-1 = 1, 3-2 = 1, and 4-3 = 1.
Function Description
Write a function pairs. It must return an integer representing the number of element pairs having the required difference.
Pairs has the following parameter(s):
- k: an integer, the target difference
- arr: an array of integers
Input Format
- The first line contains two space-separated integers n and k, the size of arr and the target value.
- The second line contains n space-separated integers of the array arr.
Sample Input
5 2
1 5 3 4 2
Sample Output
3
#include <stdio.h> int countPairsWithDiffK(int arr[], int n, int k) { int count = 0; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { if (arr[i] - arr[j] == k || arr[j] - arr[i] == k ) { count++; } } } return count; } int main() { int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3, result; result = countPairsWithDiffK(arr, n, k); printf("%d",result); return 0; }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int arr[] = new int [n]; for(int i=0;i<n;i++){ arr[i] = sc.nextInt(); } int counter = 0; Set<Integer> value = new HashSet<>(); for(int i : arr){ value.add(i); } for(int i : value){ if(value.contains(i + k)){ ++counter; } } System.out.println(counter); } }
def pairs(k, arr): q = 0 n = len(arr) arr = set(arr) h = len(arr) - n for i in arr: if i+k in arr: q+=1 return q+h nk = input().split() n = int(nk[0]) k = int(nk[1]) arr = list(map(int, input().rstrip().split())) result = pairs(k, arr) print(result)
Question 14
Problem Statement:- A jail has several prisoners and several treats to pass out to them. Their jailer decides the fairest way to divide the treats is to seat the prisoners around a circular table in sequentially numbered chairs. A chair number will be drawn from a hat. Beginning with the prisoner in that chair, one candy will be handed to each prisoner sequentially around the table until all have been distributed.
The jailer is playing a little joke, though. The last piece of candy looks like all the others, but it tastes awful. Determine the chair number occupied by the prisoner who will receive that candy.
For example, there are 4 prisoners and 6 pieces of candy. The prisoners arrange themselves in seats numbered 1 to 4. Let’s suppose two are drawn from the hat. Prisoners receive candy at positions 2,3,4,1,2,3. The prisoner to be warned sits in chair number 3
Function Description
Write a function to save the prisoner. It should return an integer representing the chair number of the prisoner to warn.
save the prisoner has the following parameter(s):
- n: an integer, the number of prisoners
- m: an integer, the number of sweets
- s: an integer, the chair number to begin passing out sweets from
Input Format
- The first line contains an integer t, denoting the number of test cases.
- The next t lines each contain 3 space-separated integers:
- -: n the number of prisoners
- -: m the number of sweets
- -: s the chair number to start passing out treats at
Output Format
- For each test case, print the chair number of the prisoner who receives the awful treat on a new line.
Sample
2
5 2 1
5 2 2
Sample Output
2
3
#include <stdio.h> int main() { int t,j,i,count=0; long int ncr; long int result,diff; scanf("%d",&t); long int n[t]; long int m[t]; long int s[t]; for(i=0;i=m[i]) { result=(s[i]+m[i])-1; printf("%ld\n",result); } if(count n[i]) { diff=diff-n[i]; } printf("%ld\n",diff); } } return 0; }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); int arr[] = new int [T]; int i = 0; while (T-- > 0) { int N = scan.nextInt(); int M = scan.nextInt(); int S = scan.nextInt(); int last = ((M - 1) + (S - 1)) % N + 1; arr[i] = last; i+=1; } scan.close(); for(int z=0;z<arr.length;z++) { System.out.println(arr[z]); } } }
def saveThePrisoner(n, m, s): if (m + s - 1) % n == 0: return n else: return (m+s-1) % n t = int(input()) for t_itr in range(t): nms = input().split() n = int(nms[0]) m = int(nms[1]) s = int(nms[2])result = saveThePrisoner(n, m, s) print(result)
Get over 200+ 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
Login/Signup to comment
29 comments on “TCS Digital Advanced Coding Questions and Answers 2023”
30+ Companies are Hiring
Get Hiring Updates right in your inbox from PrepInsta
In question number 2 what happens if the input given is 2 3 5 4 1 it should not include the 4th level it included the 5th level
I think the correct code is
int main()
{
int n;scanf(“%d”,&n);
int arr[n];
for(int i=0;i<n;i++) scanf("%d",&arr[i]);
int i=0,rewards=0;
while(i<n){
int k=0;
int j=i,max = arr[i];
while(j=max){ max=arr[j]; k++;}
j++;
}
if(k>rewards) rewards = k;
i++;
}
printf(“%d”,rewards);
return 0;
}
Join our TA Support Group on Discord, where we will help you out with all your queries:
Discord
Kindly join our Discord if you have any technical query : Discord
Join us on our Discord Channel if you have any technical query : Discord
q-8, same problem is on hackerrank by name of “Save the prisoner”. Shortest code is this:
#include
using namespace std;
int main()
{
long long t,n,m,s;
cin>>t;
while(t–)
{
cin>>n>>m>>s;
cout<<(((s-1+m-1)%n)+1)<<endl;
}
}
q-6, for those who are wondering what M list/array represents, it represents the different values for (6-m)^2 for each month m and D list/array represents the different values for |d-15| for each date d and MM list/array represents the total no. of days in each month.
Q-5, same problem is on hackerrank by the name of “Drawing Book”. In the discussion section and everywhere the same formula is used with no explanation. I have done the question without using the formula on my blog and put the solution with explanation. Check out here: https://makingcodesimple.blogspot.com/2020/11/Hackerrank-BillDivision-SalesbyMatch-DrawingBook-solutions.html
Q-1(easy):
n=int(input())
p=3
q=2
no=6
for i in range(n):
for j in range(i+1):
print(‘%.5d’%no, end=” “)
p+=4
q+=2
no=p*q
print()
Q-3:
from num2words import num2words as n2w
from itertools import combinations as com
n=int(input())
n_list=list(map(int,input().split()))[:n]
v=[‘a’,’i’,’e’,’o’,’u’]
s=0
for nl in n_list:
for letter in n2w(nl):
if letter in v:
s+=1
out=0
for c in com(n_list,2):
if sum(c)==s:
out+=1
print(n2w(out))
Q1
n=int(input())
a=1
for j in range(1,n+1):
for i in range(1,j+1):
re=2*a*(4*a-1)
a=a+1
print(‘%.5d’%re,end=’ ‘)
print()
Q-1 correct answer for java program.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int n,i,j,o=3,e=0,s=0;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
e+=2;
if(i==1)
{
o=3;
}
else{
o+=4;
}
s=(e*o);
System.out.format("%05d ",s);
}
System.out.println();
}
}
}
Prisoner
#include
int main()
{
int d=0,a[10],b[10],c[10],n,i;
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
scanf("%d%d%d",&a[i],&b[i],&c[i]);}
for(i=0;ia[i])
{
d=d-a[i];
}
printf(“%d\n”,d);
}
}
solution 1:
//identify logic in series
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int e=2,f=3;
int n=sc.nextInt();
//int s=n*(n+1)/2;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
int a=e*f;
String formattedStr = String.format("%05d", a);
System.out.print(formattedStr + " ");
// System.out.print(0005a+" ");
e+=2;
f+=4;
}
System.out.println();
}
}
}