- Prepare
- All Platforms
- Programming
- Aptitude
- Syllabus
- Interview Preparation
- Interview Exp.
- Off Campus
- Prime Video
- Prime Mock

- PrepInsta Prime
- OffCampus
- The Job Company
- Placement Stats
- Prime Video
- Prime Mock

^{0}Notifications Mark All Read

No New notification

- Login
- Get Prime

TCS NQT Menu

- Placement Papers
- What is TCS NQT?
- How To Apply
- Foundation Section
- Aptitude Questions
- English Verbal
- Reasoning Ability
- Advanced Section
- Advanced Quantitative Ability
- Advanced Reasoning Ability
- Advanced Coding
- Coding Questions
- Syllabus 2024
- Recruitment Process
- Registration Process
- Eligibility Criteria
- How to prepare for TCS NQT?
- Interview Questions
- Hiring Process

# TCS NQT Advanced Coding Questions and Answers

**TCS NQT Advanced Coding Questions and Answers**

TCS NQT advanced coding questions and answers is a sub section of TCS NQT advanced section, which is recently introduced by TCS in their placement drive.

We have discussed TCS NQT Advanced Coding Questions and answers along with detailed analysis, with importance, difficulty, and TCS NQT Advanced Coding frequently asked questions.

## Details regarding TCS NQT Advanced Coding Round

Details | Coding Round |
---|---|

Number of Questions | 3 questions |

Time Limit | 90 mins |

Difficulty Level | Hard |

## Practice TCS NQT Advanced Coding Questions with Solutions Set 1

Use Coupon Code “**CT10**” and get flat 10% OFF on Prime, additionally get one month subscription.

**Question 1**

Alice and her friends are playing a game of verbal Kho-Kho. Alice is acting as a mediator, and the rest of the N friends are seated on N chairs, one each.

Alice starts by providing a paper with a single-digit number to the friend present at number 1. Let’s denote friends by F, where F will be of size N. F[1]…F[N] represents friends seated respectively. After receiving the paper with a digit, F[1] will enact and try to tell F[2] without speaking. Similarly, F[2] will communicate to the next person i.e., F[3]. This continues until the last person F[N] understands the digit. Finally, the last person will write the digit on a separate paper and give it to Alice to compare both papers. If the digits are similar then, Alice will give a T-shirt to each friend. However, if the digits do not match, Alice will ask each friend’s digits, and she will offer the T-shirts to only those who understood the digits correctly.

Given N number of friends and digit array D, denoting the digit understood by each friend F. finds out how many of Alice’s friends have not enacted well OR did not understand the enactment by the previous friend correctly.

**Example 1:**3 -> N, number of friends

4 4 4 – array D. denoting digit understanding by N friends

**Output:**

0

**Explanation:**

All of them understood the digits correctly.

**Example 2:**5

1 2 3 2 2

**Output:**

4

**Explanation:**

1st, 2nd, 3rd, and 4th friends could not enact OR understand the enactment.

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

#include<iostream> using namespace std; int main() { int n, z = 0; cin>>n; int arr[n]; for(int i = 0; i < n; i++) { cin>>arr[i]; } for(int i = 1; i < n; i++) { if(arr[0]==arr[i]) z++; } cout << n-z-1; return 0; }

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

n = int(input()) arr = list(map(int, input().split())) print(n-arr.count(arr[0]))

**Question 2**

Bob is going to bet today on horse riding. There are N horses listed in a sequence of 1 to N.

The probability of winning each horse is different so the prices for making a bet on the horses are not the same. There is no limit on the number of horses on which he can bet, but he thinks that if he bets on a continuous sequence of horses then he has a better chance to win. Bob will get K units of money if any horse on which he bets will win. But as the award is only K units so he wants to put money less than K. Bob wants to bet on as many horses as he can. As you are his best friend, he reached out to you for help, can you please find the length of the maximum continuous sequence of horses on which Bob can make a bet, and remember he will invest money less than K units. If there is more than one possible combination, Bob will bet randomly on any one of them.

Given the number of horses(N), reward money(K), and price of betting on N horses in order.

**Hint:** For each starting index of a horse, its end index in sequences will be equal to or greater than the end index of the previous starting index.

**Example 1:**

**Input:**

90 100 -> N = 10, K=100

30 40 50 20 20 10 90 10 10 10 -> Price to make bet on each horse in order**Output:**

3**Explanation:**

There are 10 horses, and the reward money is 100. So, Bob will put money in less than 100. There are two possible o sequences of length three whose total money for betting is less than 100, i.e. [50 20 20] (sum is 90) and [10 10 10] (sum is 30). Bob will choose randomly one sequence from these two. As none of the other sequences with a length greater than 3 will have a price less than 100 so the answer will be 3.

**Example 2:**

**Input:**10 100 -> N = 10, K=100

10 90 80 20 90 60 40 60 70 75 -> Price to make bet on each horse in order

**Output:**1

**Explanation:**

There are no two consecutive horses for which the sum of price is less than 100. So, Bob will choose randomly any one horse. And the max length of the sequence will be 1.

**Constraints:**

- 2<=N<=105
- 1<= K<=109
- 1<=A1, A3… AN<=109

**The Input format for testing:**

The candidate has to write the code to accept 2 inputs.

**First Input:**It will contain two integers N (number of horses) and K (reward money)**Second Input:**It will contain N integers, each separated

#include<bits/stdc++.h> using namespace std; int main() { int n,k,sum=0,ans=0,maxi=INT_MIN,m; cin>>n>>k; int a[n]; for(int i=1; i<=n;i++){ cin>>a[i]; } for(int i=1;i<=n;i++){ sum+=a[i]; for(int j=i;j<=n;j++){ sum+=a[j]; if(sum<=k){ m=j-i+1; maxi =max(maxi,m); } else{ break; } } } cout<<maxi<<"\n"; return 0; }

def fun(n, k, arr): ans = 0 if min(arr) < k: ans = 1 for i in range(n - 1): for j in range(i + 1, n): if sum(arr[i:j]) < k: ans = max(ans, j - i) else: break return ans n, k = map(int, input().split()) arr = list(map(int, input().split())) print(fun(n, k, arr))

**Question 3**

This vacation you went to visit the golden house. There are N rooms in this golden house and its owner needs someone to take care of the management of this house. As you have been unemployed for a long time, you are interested in this job. The owner of this house wanted an intelligent manager for this role, so he created one puzzle within that golden house. The person who will be able to solve that puzzle will be the manager of the golden house.

The owner of the house kept some number of golden coins in each room. You have to choose two rooms, one from where you will enter and the other one from where you will exit. From any room either you can exit, or you can move to the next room. While visiting any room you will collect all the gold coins, and if you enter any room then you can’t skip collecting gold coins from that room, you have to take those coins. The owner wants to have exactly K coins, when you exit the room, he guarantees that there will be at least one possible solution for this puzzle.

Given several rooms (N), and several gold coins in N rooms. You have to find room numbers from where you will start and from where you will exit. If there is more than one solution possible, then you have to provide a solution with a smaller starting room number.

You can assume that room numbers will start from 1 and end at N.

**Hint:** Find a continuous subsequence whose sum will be exactly equal to K.

**Example 1:**

**Input:**

10 15 -> N =10, K = 15

5 3 7 14 18 1 18 4 8 3 -> Number of gold coins in each room.**Output:**

1 3**Explanation:**There are ten rooms in the house. You want to have the Total sum of gold coins in a continuous sequence of rooms to be 15 There are two solutions to this i.e. [1, 3] and [8, 10] then the solution with a smaller starting room number will be printed hence [1, 3] is output.

def fun(n, k, arr): for i in range(n - 1): for j in range(i, n): if sum(arr[i:j]) == k: return [i + 1, j] n, k = map(int, input().split()) arr = list(map(int, input().split())) s = fun(n, k, arr) print(s[0], s[1])

**Question 4**

Tina was given a piece of silk cloth. There are already a few points or coordinates mentioned on it. She is creating something which needs an exact square shape cloth. Help Tina to find out how many minimum points she can add, to cut the perfect square from the given cloth.

There are already a few points marked on one cloth, Tina has to include the most number of points from the given points and should try to include the minimum number of points or coordinates from her side.

Find the minimum number of coordinates to achieve the perfect square. Also, try to get as bigger cloth as possible.

Let us try to understand it with an example

Let’s say there are 3 points given means N=3

These points are:

Let us try to understand it with an example Let’s say there are 3 points given, which means N=3 These points are

00

22

33

We can have 2 additional coordinates:

- (2,0) & (0,2)

OR - (3,0) & (0,3)

Tina doesn’t want to lose a good deal here, so better if she would go with (3,0) & (0,3). Hence 2 additional coordinates were required to cut a perfect square from that piece of cloth.**Hence the answer is 2**

**Example 1:**

**Input:**

5 -> Input integer, N

0 0 -> Input integer, x[i], y[i]

100 100 -> Input integer, x[i], y[i]

200 200 -> Input integer, x[i], y[i]

100 0 -> Input integer, x[i], y[i]

0 100 ->Input integer, x[i], y[i]**Output:**

0 -> Output**Explanation:**

In the above scenario, we can already make a square from the given coordinates

P1: (0, 0)

P2: (100, 0)

P3: (0, 100)

P4: (100, 100)

Hence no need for any additional coordinates here.**So the answer is No.**

**Example 2:**

**Input:**

3 -> Input integer. N

00 -> Input integer, x[i], y[i]

22 -> Input integer, x[i], y[i]

33 -> Input integer, x[i], y[i]**Output:**

2 -> Output**Explanation:**

In the above scenario, we can have 2 additional co-ordinates:

- (20)&(0,2)

OR - (3,0)&(0.3)

- (20)&(0,2)

Tina doesn’t want to lose a good deal here so better if she would go with (3,0), (0,3).

Hence 2 additional co-ordinates were required to cut a perfect square from that piece of cloth.**Hence the answer is 2.**

from itertools import combinations def fun(n, arr): if n < 3: return 4 - n elif n == 3: if distSq(arr[0], arr[1]) == distSq(arr[1], arr[2]) == distSq(arr[0], arr[2]): return 1 else: return 2 else: arrr = com(4, arr) for i in arrr: if isSquare(i[0], i[1], i[2], i[3]): return 0 arrr = com(3, arr) for i in arrr: print(i) if distSq(i[0], i[1]) == distSq(i[1], i[2]) == distSq(i[0], i[2]): return 1 return 2 def isSquare(p1, p2, p3, p4): d2 = distSq(p1, p2) d3 = distSq(p1, p3) d4 = distSq(p1, p4) if d2 == 0 or d3 == 0 or d4 == 0: return False if d2 == d3 and 2 * d2 == d4 and 2 * distSq(p2, p4) == distSq(p2, p3): return True if d3 == d4 and 2 * d3 == d2 and 2 * distSq(p3, p2) == distSq(p3, p4): return True if d2 == d4 and 2 * d2 == d3 and 2 * distSq(p2, p3) == distSq(p2, p4): return True return False def com(n, arr): a = [] comb = combinations(arr, n) for i in comb: a.append(list(i)) return a def distSq(p, q): return (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]) N = int(input()) ar = [] for i in range(N): ar.append(list(map(int, input().split()))) print(fun(N, ar))

**Question 5**

Jack is a sports teacher at St. Patrick’s School. He makes games not only to make the student fit but So smart. So, he lined up all the N number classes. of students in his class. At each position, he has fixed a board with the Integer number printed on it. Each number is unique and in exactly the range of N. Let us say there are 10 students, then the boards will be printed with numbers from 1 to 10 in a random order given by the sequence A[ ]. As a rule, all students wear a jersey with their numbers printed on it. So if there are students, each will have a unique jersey number just like a football team. Now, in the beginning, all the students will stand as per the increasing order of their jersey numbers, from left to right. The only difference will be their respective board number which is placed at their respective location. The board location is fixed and cannot be changed. We can consider the arrangement as below. Suppose there are students, and the board is placed in the order of [2 3 1 5 4].

Board — 2, 3, 1, 5, 4

Student’s Jersey — 1, 2, 3, 4, 5

Now the game begins.

- After every beat of the drum, each student will have to move to that location (index), where his board is pointing to. In the above case student with jersey #1 is standing with board #2, so now he will have to move to location #2. Similarly, all the other students will do.

So after the first beat of the drum, the alignment will be:

Board — 2, 3, 1, 5, 4.

This keeps going on and on until all the students are back to the way they were at the beginning. So, after 6 beats of the drum, all the students will be aligned the same way as before.

Given N and the order of the board of the respective positions, find the number of beats required to bring back the students to their original position.

So, for the above case, the answer is 6

**Example 1:**

**Input:**

3 -> Input integer, N

{1, 2, 3} ->Input integer. B[], board alignment.**Output:**

1 -> Output**Explanation:**

All the students will be standing in board positions;

Board — 1, 2, 3

Student’s Jersey –1, 2, 3After the first beat of the drum:

Jersey #1 will move to index 1.

Jersey #2 will move to index 2.

Jersey #3 will move to index 3.

Hence, they will be back in their position in just 1 beat.**So, the answer is 1.**

**Example 2:**

**Input:**

5 -> Input integer, N

{2, 3, 1, 5, 4} -> Input integer, B[ ], board alignment.**Output:**

6 -> Output**Explanation:**

All the students will be standing as below, with the board positions:

Board — 2, 3, 1, 5, 4

Student’s Jersey — 1, 2, 3, 4, 5After Beat-1of the drum:

Jersey #1 has moved to index 2.

Jersey #2 has moved to index 3.

Jersey #3 has moved to index 1.

Jersey #4 has moved to index 5.

Jersey #5 has moved to index 4.Board – 2, 3, 1, 5, 4

Student’s Jersey — 3, 1, 2, 5, 4After Beat-2 of the drum:

Jersey #3 has moved to index 2.

Jersey #1 has moved to index 3.

Jersey #2 has moved to index 1.

Jersey #5 has moved to index 5.

Jersey #4 has moved to index 4.Board — 2, 3, 1, 5, 4

Student’s Jersey — 2, 3, 1, 4, 5After Beat-3 of the drum:

Board — 2, 3, 1, 5, 4

Student’s Jersey — 1, 2, 3, 5, 4

After Beat-4 of the drum:

Board — 2, 3, 1, 5, 4

Student’s Jersey — 3, 1, 2, 4, 5After Beat-5 of the drum:

Board — 2, 3, 1, 5, 4

Student’s Jersey — 2, 3, 1, 5, 4After Beat-6 of the drum:

Board — 2, 3, 1, 5, 4

Student’s Jersey — 1, 2, 3, 4, 5Hence, they will be back in their positions after 6 beats.

**So, the answer is 6.**

n = int(input()) B = [] arr = [] for i in range(n): B.append(int(input())) arr.append(i + 1) ans = 0 while 1: ans += 1 ar = [None] * n for i in range(n): ar[i] = arr[B[i] - 1] if ar == sorted(ar): break arr = ar print(ans)

**Question 6**

Ayush is working on a strange algorithm where he wants to convert a string from A to B, both the strings of equal length N

Below are the rules which can be performed to convert a string

- String A and B are of equal length
- Both of them are in lower case
- Choose a subset X from the string A, between the index 1 and N.
- Let ‘s’ be the letter that alphabetically comes before all other letters in the subset. Let ‘s’ be called the ‘smallest element’ in the subset.
- Replace all the elements of the subset with the letter ‘s’

Find the minimum number of moves which is required to perform the conversion. If it is not possible to convert the string from A to b then return -1

Let us try to understand it with examples Suppose there are 2 strings

A = abcab

B = aabab

Operation 1: 2

Now we have chosen a subset S, let us say we have taken indexes 2,3,5 from A then the subset S becomes [bcb]. Next, we have to choose the smallest element, 6041 here, which is b here in b & c. Next, we have to replace all the other elements in the subset with this element. So ‘b’ with replace everything in [bcb]. which becomes [bbb]. Now we will place all the respective elements back in their respective index. This will update the original string as [abbab].

Operation 2:

Original string [abbab]. Now we have chosen a subset S, let’s say we have taken an index 1,2,4 from A then the subset becomes [aba]. Next, we have to choose the smallest element, which is here in a & b. Next, we have to replace the smallest with all the other elements in the subset. So ‘a’ will replace everything in [aba]. Now we will place all the respective elements back in their respective index. This will update the original string as [aabab]. This is the same as String B. Hence it is possible to convert string A to B, with 2 operations.

So, the answer is 2.

**Example 1:**

**Input:**

2 -> Input integer, N

de -> input string, A

cd -> Input string, A

**Output:**-1 -> Output

**Explanation:**

In the above example, we can see that there is an alphabet in A which is completely different from B. hence it is not possible to convert A to B

So the answer is -1

**Example 2:**

**Input:**

4-> input integer, N

abab-> input string, A

abaa-> input string A

**Output:**

1 -> Output

**Explanation:**

Operation 1:

Now we have chosen a subset S, let’s say we have taken

index 3, 4 from A

Then Subset S becomes [ab]

Next, we have to choose the smallest element, which is a here in a & b

Next, we have to replace the smallest with all the other elements in a subset. So ‘a’ will replace everything in [abl, which becomes [aa]

Now we will place all the respective elements back in their respective index. This will update the original string as [abaa]

This is the same as String B

Hence it is possible to convert string A to B. with 1 operation. So, the answer is 1.

#include<bits/stdc++.h> using namespace std; int minCost(string str1, string str2, int n) { int cost = 0; for (int i = 0; i < n; i++) { if (str1[i] != str2[i]) { if (i < n - 1 && str1[i + 1] != str2[i + 1]) { swap(str1[i], str1[i + 1]); cost++; } else { cost++; } } } return cost; } int main() { string str1 = "abb", str2 = "bba"; int n = str1.length(); cout << minCost(str1, str2, n); return 0; }

n = int(input()) a = input() b = input() if a == b: print(1) res, res2 = "", "" for x in range(n): if a[x] != b[x]: res += a[x] res2 += b[x] ans = 0 for i in a: if ans != 0: break if i not in b: print(-1) break else: for x in set(res2): if x not in a: print(-1) ans += 1 break else: print(len(set(res2))) ans += 1 break if ans == 1: break

**Question 7**

At the security checkpoint, airport security personnel have seized a number of travellers’ belongings. Everything has been thrown into a big box (array). Each product carries a specific level of risk[0,1,2]. The risk severity of the items in this case is represented by an array[] of N integer values. Sorting the elements in the array according to the degrees of danger is the task at hand. Between 0 and 2 are the risk values.

**Example** :

**Input :**

7 -> Value of N

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

**Output :**

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

**Example 2:**

input : 10 -> Value of N

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

**Output : **

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

**Explanation:**

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

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

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

**Question 8**

For all of its products, a supermarket maintains a pricing structure. Each product has a value N printed on it. The price of the item is determined by multiplying the value N, which is read by the scanner, by the sum of all its digits. The goal here is to create software that, given the code of any item N, will compute the product (multiplication) of all the value digits (price).

**Example 1:**

**Input :**

5244 -> Value of N

**Output :**160 -> Price

**Explanation:**

From the input above

Product of the digits 5,2,4,4

5*2*4*4= 160

Hence, output is 160.

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

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

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

**Question 9**

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 the 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 = loan amount * monthly interest rate / ( 1 – 1 / (1 + monthly interest rate)^(number of years * 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. The 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 interest rate and their period.
- 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 a single white space.

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

**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<bits/stdc++.h> using namespace std; int main() { int year, principal, installments; float bank[2], roi, square, emi, sum; cin >> principal; cin >> year; for(int i = 0; i < 2; i++) { cin >> installments; sum = 0; for(int j = 0; j < installments; j++) { cin >> year >> roi; square = pow((1+roi),year*12); emi = (principal*(roi)/(1-1/square)); sum += emi; } bank[i] = sum; } if(bank[0] < bank[1]) cout << "Bank A"; else cout << "Bank B"; }

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[5]; 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[0] < bank[1]) System.out.println("Bank A"); else System.out.println("Bank B"); } }

bank = [] principal = int(input()) year = int(input()) for i in range(2): installments = int(input()) sum = 0 for i in range(0, installments): year, roi = map(float,input().split()) year = int(year) square = pow((1+roi),year*12) emi = (principal*(roi)/(1-1/square)) sum = sum + emi bank.append(sum) if bank[0] < bank[1]: print("Bank A") else: print("Bank B")

**Question 10**

Some prime numbers can be expressed as a sum of other consecutive prime numbers. For example 5 = 2 + 3, 17 = 2 + 3 + 5 + 7, 41 = 2 + 3 + 5 + 7 + 11 + 13. Your task is to find out how many prime numbers which satisfy this property are present in the range 3 to N subject to a constraint that summation should always start with number 2.

Write code to find out the number of prime numbers that satisfy the above-mentioned property in a given range.

**Input Format:** First line contains a number N

**Output Format:** Print the total number of all such prime numbers which are less than or equal to N.

**Constraints :** 2<N<=12,000,000,000

**Example :**

**Input :**

20

**Output :**

2

**Explanation :**

Below 20, there are 2 such numbers,

5=2+3

17=2+3+5+7

#include<bits/stdc++.h> using namespace std; map<int,int> prime; vector pr; int ans=0,n; int main() { cin>>n; prime[0]=1; for(int p = 2; p <= n; p++) { if (prime[p] == 0) { pr.push_back(p); for (int i = p*p; i <= n; i += p) prime[i] =1; } } int sum=2; for(int i=1;i<pr.size();i++) { sum+=pr[i]; if(sum>n) break; if(prime[sum]==0) {ans++;} } cout<<ans; }

public class Main { public static void main(String[] args) { int n = 45; boolean prime[] = new boolean[n + 1]; vector primevector = new vector<>(); for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p <= n; p++) { if(prime[p] == true) { primevector.add(p); for(int i = (p * p); i <= n; i += p) prime[i] = false; } } int count = 0; int sum = primevector.elementAt(0); for (int i = 1; i < primevector.size(); i++) { sum += primevector.elementAt(i); if(sum > n) break; if(prime[sum] == true) { count++; } } System.out.println(count); } }

**Question 11**

Juan Marquinhos is a geologist and he needs to count rock samples to send them to a chemical laboratory. He has a problem: The laboratory only accepts rock samples in a range of its size in ppm (parts per million).

Juan Marquinhos receives the rock samples one by one and he classifies the rock samples according to the range of the laboratory. This process is very hard because the number of rock samples may be in the millions.

Juan Marquinhos needs your help, your task is to develop a program to get the number of rocks in each of the ranges accepted by the laboratory.

**Input Format**

A positive integer S (the number of rock samples) separated by a blank space, and a positive integer R (the number of ranges of the laboratory); A list of the sizes of S samples (in ppm), as positive integers separated by space R lines where the ith line containing two positive integers, space separated, indicating the minimum size and maximum size respectively of the ith range.

**Output Format**

R lines where the ith line contains a single non-negative integer indicating the number of the samples which lie in the ith range.

**Constraints**

- 10 < S < 10000
- 1 < R < 1000000
- 1 size of each sample (in ppm) < 1000

**Example 1**

Input: 10 2

345 604 321 433 704 470 808 718 517 811

300 350

400 700

**Output**: 2 4

**Explanation:**

There are 10 samples (S) and 2 ranges ( R ). The samples are 345 604 321 433 704 470 808 718 517 811. The ranges are 300-350 and 400-700. There are 2 samples in the first range (345 and 321) and 4 samples in the second range (604, 433, 470, 517). Hence the two lines of the output are 2 and 4

**Example 2**

**Input:** 20 3

921 107 270 631 926 543 589 520 595 93 873 424 759 537 458 614 725 842 575 195

1 100

50 600

1 1000

**Output**: 1 12 20

**Explanation:**

There are 20 samples and 3 ranges. The samples are 921, and 107 195. The ranges are 1-100, 50-600, and 1-1000. Note that the ranges are overlapping. The number of samples in each of the three ranges is 1, 12, and 20 respectively. Hence the three lines of the output are 1, 12, and 20.

#include <bits/stdc++.h> using namespace std; int main() { int s,r,a,b,ans; cin>>s>>r; vector<int> ansv; unordered_map<int,int> m; for(int i=0;i<s;i++) { cin>>a; m[a]++; } for(int i=0;i<r;i++) { cin>>a>>b; ans=0; for(int j=a;j<=b;j++) if(m[j]) ans++; ansv.push_back(ans); } for(auto i:ansv) cout<<i<<" "; }

import java.util.*; class Main { public static void main(String[] args) { { int n, range, count = 0; Scanner sc = new Scanner(System.in); n = sc.nextInt(); int arr[] = new int[n]; range = sc.nextInt(); for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); range = range * 2; for (int i = 0; i < range; i = i + 2) { int arrrange[] = new int[range]; arrrange[i] = sc.nextInt(); arrrange[i + 1] = sc.nextInt(); for (int j = 0; j < n; j++) { if ((arr[j] >= arrrange[i]) && (arr[j] <= arrrange[i + 1])) count++; } System.out.println(count); count = 0; } } } }

from collections import defaultdict D=defaultdict(int) AnsString="" s,r=map(int,input().split()) L=list(map(int,input().split())) for i in L: D[i]=1 for i in range(r): a,b=map(int,input().split()) ans=0 for j in range(a,b+1): if D[j]: ans+=1 AnsString+=str(ans)+" " print(AnsString)

## Practice TCS NQT Advanced Coding Questions with Solutions Set 2

**Question 1: K-****th largest factor of N**

**th largest factor of N**

A positive integer d is said to be a factor of another positive integer N if when N is divided by d, the remainder obtained is zero. For example, for number 12, there are 6 factors 1, 2, 3, 4, 6, 12. Every positive integer k has at least two factors, 1 and the number k itself.Given two positive integers N and k, write a program to print the kth largest factor of N.

**Input Format: **The input is a comma-separated list of positive integer pairs (N, k)

**Output Format: **The kth highest factor of N. If N does not have k factors, the output should be 1.

**Constraints: **1<N<10000000000. 1<k<600.You can assume that N will have no prime factors which are larger than 13.

**Example 1**

**Input**: 12,3**Output**: 4

**Explanation: **N is 12, k is 3. The factors of 12 are (1,2,3,4,6,12). The highest factor is 12 and the third largest factor is 4. The output must be 4

**Example 2**

**Input**: 30,9**Output**: 1

**Explanation: **N is 30, k is 9. The factors of 30 are (1,2,3,5,6,10,15,30). There are only 8 factors. As k is more than the number of factors, the output is 1.

#include<bits/stdc++.h> using namespace std; vector<int> a,ans; void Find_Factor(int f,int i) { if(f>sqrt(a[0])) return; if(a[0]%f) { Find_Factor(f+i,i);return; } ans.push_back(f); Find_Factor(f+i,i); if(f*f!=a[0]) ans.push_back(a[0]/f); } int main() { string s;getline(cin,s); int n,k; istringstream ss(s); for(int i;ss>>i;) { a.push_back(i); if(ss.peek()==',') ss.ignore(); } ans.push_back(1); if((a[0]&1)==0) Find_Factor(2,1); else Find_Factor(3,2); ans.push_back(a[0]); //for(auto i:ans) cout<<i<<" "; if(ans.size()<a[1]) cout<<1; else cout<<ans[ans.size()-a[1]]; }

import java.util.*; class Main { public static void main(String[] args) { { int n, k, i, c = 0; Scanner sc = new Scanner(System.in); n = sc.nextInt(); k = sc.nextInt(); for (i = n; i >= 1; i--) { if ((n % i) == 0) c++; if (c == k) { System.out.println(i); break; } } if (c != k) System.out.println("1"); return ; } } }

def Find_Factor(f,i,n,ans): if f*f>n: return if (n%f): Find_Factor(f+i,i,n,ans) return ans.append(f) Find_Factor(f+i,i,n,ans) if (f*f)!=n: ans.append(n//f) n,k=map(int,input().split(",")) ans=[] ans.append(1) if n&1: Find_Factor(3,2,n,ans) else: Find_Factor(2,1,n,ans) ans.append(n) if(len(ans)<k): print(1) else: print(ans[len(ans)-k])

**Question 2: Collecting Candies**

Krishna loves candies a lot, so whenever he gets them, he stores them so that he can eat them later whenever he wants to.

He has recently received N boxes of candies each containing Ci candies where Ci represents the total number of candies in the ith box. Krishna wants to store them in a single box. The only constraint is that he can choose any two boxes and store their joint contents in an empty box only. Assume that there are an infinite number of empty boxes available.

At a time he can pick up any two boxes for transferring and if both the boxes contain X and Y number of candies respectively, then it takes him exactly X+Y seconds of time. As he is too eager to collect all of them he has approached you to tell him the minimum time in which all the candies can be collected.

**Input Format:**

- The first line of input is the number of test case T
- Each test case is comprised of two inputs
- The first input of a test case is the number of boxes N
- The second input is N integers delimited by whitespace denoting the number of candies in each box

**Output Format: **Print minimum time required, in seconds, for each of the test cases. Print each output on a new line.

**Constraints:**

- 1 <T<10
- 1 <N<10000
- 1 < [Candies in each box] < 100009

**Input :**

1

4

1 2 3 4

**Output :**

19

**Explanation :**

4 boxes, each containing 1, 2, 3 and 4 candies respectively.Adding 1 + 2 in a new box takes 3 seconds.Adding 3 + 3 in a new box takes 6 seconds.Adding 4 + 6 in a new box takes 10 seconds.Hence total time taken is 19 seconds. There could be other combinations also, but overall time does not go below 19 seconds.

#include<bits/stdc++.h> using namespace std; int main() { int t;cin>>t; vector<int> ans; while(t--) { int n,a;cin>>n; priority_queue<int,vector<int>,greater<int>> pq; for(int i=0;i<n;i++) {cin>>a;pq.push(a);} a=0; while(pq.size()>1) { int k1=pq.top();pq.pop(); k1+=pq.top();pq.pop(); a+=k1;pq.push(k1); } ans.push_back(a); } for(auto i:ans) cout<<i<<endl; }

import heapq as hq t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) hq.heapify(a) s=0 for j in range(n-1): b=hq.heappop(a) c=hq.heappop(a) s+=(b+c) hq.heappush(a,b+c) print(s)

**Question 3: Square Free Numbers**

In the theory of numbers, square free numbers have a special place. A square free number is one that is not divisible by a perfect square (other than 1). Thus 72 is divisible by 36 (a perfect square), and is not a square free number, but 70 has factors 1, 2, 5, 7, 10, 14, 35 and 70. As none of these are perfect squares (other than 1), 70 is a square free number.

For some algorithms, it is important to find out the square free numbers that divide a number. Note that 1 is not considered a square free number.

In this problem, you are asked to write a program to find the number of square free numbers that divide a given number.

**Input**

- The only line of the input is a single integer N which is divisible by no prime number larger than 19

**Output**

- One line containing an integer that gives the number of square free numbers (not including 1)

**Constraints**

- N < 10^9

**Complexity**

Simple

**Time Limit**

1

**Example 1**

**Input**

20

**Output**

3

**Explanation**

N=20

If we list the numbers that divide 20, they are

1, 2, 4, 5, 10, 20

1 is not a square free number, 4 is a perfect square, and 20 is divisible by 4, a perfect square. 2 and 5, being prime, are square free, and 10 is divisible by 1,2,5 and 10, none of which are perfect squares. Hence the square free numbers that divide 20 are 2, 5, 10. Hence the result is 3.

**Example 2**

**Input**

72

**Output**

3

**Explanation**

N=72. The numbers that divide 72 are

1, 2, 3, 4, 6, 8, 9, 12, 18, 24, 36, 72

1 is not considered square free. 4, 9 and 36 are perfect squares, and 8,12,18,24 and 72 are divisible by one of the. Hence only 2, 3 and 6 are square free. (It is easily seen that none of them are divisible by a perfect square). The result is 3

#include< bits/stdc++.h> using namespace std; int main() { int N,c=0; //c is Count of Prime Factors cin>>N; vector <int> Prime={2,3,5,7,11,13,17,19}; for(auto i:Prime) if(N%i==0) c++; cout<<((1<<c)) - 1; //2^n - 1 }

import java.io.*; import java.util.*; import java.lang.Math; public class Main { public static void main(String[] args) { long n; double square; long j = 0, check; long[] temp = new long[10_000]; int total_count = 0; System.out.println("Enter the number:"); Scanner sc= new Scanner(System.in); n = sc.nextLong(); // Checking for dividends of the given number and primality for(int i = 2; i <= n / 2; i++) { if(n % i == 0) { total_count++; square = Math.sqrt(i); check = (long)square; // Checking for perfect square if(check == square) { total_count--; temp[(int)j] = i; j++; } else { for(int rem = 0; rem < j; rem++) { if(i > temp[rem] && j != 0) { if(i % temp[rem] == 0) { total_count--; rem = (int)(j + 1); } } else { break; } } } } } System.out.print(total_count); sc.close(); } }

**Question 4: Codu and Sum Love**

**Problem Description**

Given N number of x’s, perform the logic equivalent of the above Java code and print the output

Scanner sc = new Scanner(System.in); long sum = 0; int N = sc.nextInt(); for (int i = 0; i < N; i++) { final long x = sc.nextLong(); // read input String str = Long.toString((long) Math.pow(1 << 1, x)); str = str.length() > 2 ? str.substring(str.length() - 2) : str; sum += Integer.parseInt(str); } System.out.println(sum%100);

Given N number of x’s, perform logic equivalent of the above Java code and print the output

**Input**

- First line contains an integer N
- Second line will contain N numbers delimited by space

**Output**

- Number that is the output of the given code by taking inputs as specified above

**Constraints**

- 1<=N<=10^7
- 0<=x<=10^18

**Example 1**

**Input**

4

8 6 7 4

**Output**

64

**Example 2**

**Input**

3

1 2 3

**Output**

14

#include<bits/stdc++.h> using namespace std; int main() { long long int n,ans=0,x; cin >>n; for(int i=0;i<n;i++) { cin >> x; x=pow(2,x); if(x>99) ans+=x%100; else ans+=x; } cout<<ans%100; return 0; }

import java.util.Scanner; import java.lang.Math; class Main { public static void main(String[] args) { long ans = 0; Scanner scn = new Scanner(System.in); long n = scn.nextInt(); for (int i = 0; i < n; i++) { long x = scn.nextInt(); Math.pow(2, x); if (x > 99) ans += x % 100; else ans += x; } System.out.println(ans % 100); } }

n=int(input()) arr=list(map(int,input().split())) ans=0 for i in arr: x=2**i if(x>99): ans+=x%100 else: ans+=x print(ans%100)

**Question 5: Houses Problem**

There are n houses built in a line, each of which contains some value in it.

A thief is going to steal the maximal value of these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two neighbours left and right side.

What is the maximum stolen value?

**Input Format**

- First an integer n, denoting how many houses are there.
- Then n space separated integers denoting the values for the n houses.

**Output Format**

An integer denoting the maximum value possible to steal.

**Input **

7

6 7 1 3 8 2 5

**Output**

20

**Explanation**

6+1+8+5 = 20.

It is the max possible value.

#include<bits/stdc++.h> using namespace std; int n; int main() { cin>>n; vector<int> arr(n); for(int i=0;i<n;i++) cin>>arr[i]; int incl=0,excl=0,mx; for(int i=0;i<n;i++) { mx=max(incl,excl); incl=excl+arr[i]; excl=mx; } cout<<max(incl,excl); }

n=int(input()) arr=list(map(int,input().split())) incl=0 excl=0 mx=0 for i in range(n): mx=max(incl,excl) incl=excl+arr[i] excl=mx print(max(incl,excl))

**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