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

TopicsNo. of Questions
Number of Questions2
Time Limit60 mins
Difficulty levelhigh
Package Offered6.5 LPA – 7 LPA

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

Problem Statement-:

Identify the logic behind the series

6 28 66 120 190 276….

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

The Pyramid construction rules are as follows

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

Example

If input is 2, output will be

• 00006
• 00028 00066

If input is 3, output will be

• 00006
• 00028 00066
• 00120 00190 00276

Formal input and output specifications are stated below

Input Format:

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

Output Format:

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

Constraints:

• 0 < N <= 14

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

Question 2

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

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

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

Constraints:

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

Input Format:

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

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

Explanation:

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

Question 3

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 which add up to a certain digit D.

The rules to calculate digit D are as follow

• 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 input should be converted to textual representation as hundred and not as one hundred. Hence number of vowels in number 100 should be 2 and not 4

### Input

• First line contains an integer N which represents number of elements to be processed as input
• Second line contains N numbers separated by space

### Output

• Lower case representation of textual representation of number of pairs in input that sum up to digit D

Note: – (If the count exceeds 100 print “greater 100”)

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 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 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 section above.

Since no pairs add up to 5, the answer is 0. Textual representation of 0 is zero. Hence 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="zero";k="one";k="two";k="three";k="four";k="five";   k="six";k="seven";k="eight";k="nine";   k="ten";k="eleven";    k="twelve";k="thirteen";k="fourteen";k="fifteen";    k="twenty";k="thirty";k="forty";k="fifty";    k="eighty";k="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=['']*101k="zero"k="one"k="two"k="three"k="four"k="five"k="six"k="seven"k="eight"k="nine"k="ten"k="eleven"k="twelve"k="thirteen"k="fourteen"k="fifteen"k="twenty"k="thirty"k="forty"k="fifty"k="eighty"k="hundred" def vowel(s):    sum=0    for i in s:        if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':            sum+=1    return sum def findword(a):    if k[a]!="":        return k[a]    if a<20 and a>15:        k[a]=k[a%10]+"teen"        return k[a]    if a%10==0:        k[a]=k[(a//10)]+"ty"        return k[a]    if a>100:        return "greater 100"     k[a]=k[(a//10)*10]+"-"+k[a%10]    return k[a] sum1=0sum2=0n=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 Solution {      static String arr[] = new String;    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 = "zero";        arr = "one";        arr = "two";        arr = "three";        arr = "four";        arr = "five";        arr = "six";        arr = "seven";        arr = "eight";        arr = "nine";        arr = "ten";        arr = "eleven";        arr = "twelve";        arr = "thirteen";        arr = "fourteen";        arr = "fifteen";        arr = "twenty";        arr = "thirty";        arr = "forty";        arr = "fifty";        arr = "sixty";        arr = "seventy";        arr = "eighty";        arr = "ninenty";        arr = "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 4

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

```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)```
`Output201713.09.2017`
```#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;
}```
`#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; }`

Question 5

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

```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)```
```Output
8
4
2
```
```#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;
}```
`#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;}`

Question 6

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;}`
`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,0while(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-=1print(N-L)`
`import java.util.*;class Solution {      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);    }}`

Question 7

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

2

```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<Integer>();
for(int i : arr){
}
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+hnk = input().split()n = int(nk)k = int(nk)arr = list(map(int, input().rstrip().split()))result = pairs(k, arr)print(result)`
`#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);     int k = 3, result;    result = countPairsWithDiffK(arr, n, k);     printf("%d",result);    return 0; } `

Question 8

Problem Statement:- A jail has a number of prisoners and a number of 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 saveThePrisoner. It should return an integer representing the chair number of the prisoner to warn.

saveThePrisoner 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 Input

2
5 2 1
5 2 2

Sample Output

2
3

```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) % nt = int(input())for t_itr in range(t):    nms = input().split()    n = int(nms)    m = int(nms)    s = int(nms)    result = saveThePrisoner(n, m, s)    print(result)`
`#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<t;i++)    {        scanf("%ld %ld %ld",&n[i],&m[i],&s[i]);    }    for(i=0;i<t;i++)    {        count=(n[i]-s[i])+1;        if(count>=m[i])        {            result=(s[i]+m[i])-1;            printf("%ld\n",result);        }        if(count<m[i])        {            diff=m[i]-count;            while(diff>n[i])            {                diff=diff-n[i];            }            printf("%ld\n",diff);        }    }    return 0;}`

• Chirag

Q6.
public class SaveThePrisoner {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int[] arr = new int[t];
for (int i = 0; i < t; i++) {

int n = sc.nextInt();
int m = sc.nextInt();
int s = sc.nextInt();
arr[i] = savePrisoner(n, m, s);
}
for (int j = 0; j < t; j++)
System.out.println(arr[j]);
}

public static int savePrisoner(int n, int m, int s) {

return ((s+m-1)%n);
}
} 0
• Chirag

Q4.

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int n = 7;
int[] arr = { 100, 100, 50, 40, 40, 20, 10 };
int p = 4;
int[] arr1 = { 5, 25, 50, 120 };
int[] arr2 = rank(arr, n, arr1, p);
for (int i = 0; i < p; i++)
System.out.println(arr2[i]);
}

public static int[] rank(int[] arr, int n, int[] arr1, int p) {

int[] arr2 = Arrays.copyOf(arr, n);
int[] arr3 = Arrays.copyOf(arr1, p);
int max = arr;
arr2 = 1;
for (int i = 1; i arr[i]) {
arr2[i] = arr2[i – 1] + 1;
max = arr[i];
}
}
for (int k = 0; k = 0; j–) {
if (arr1[k] < arr[j]) {
arr3[k] = arr2[j] + 1;
break;
} else {
arr3[k] = arr2[j];
}
}
}
return arr3;
}

} 0
• Chirag

Q5.
public class Difference {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int p = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
System.out.println(count(arr, n, p));
}

public static int count(int[] arr, int n, int p) {

int count = 0;
for (int i = 1; i < n; i++) {
int diff = Math.abs(arr[i-1] – arr[i]);
if(diff == p)
count++;
}
return count;
}

} 0
• Abhishek

Alternate solution for Question 1 in Java (Both naive and Bottom up DP):

public class MaxMarks {
static int naiveMaxMarks(int T, int[] marks, int[] times, int n){
if (T == 0 || n == 0) return 0;
if (times[n-1] > T) return naiveMaxMarks(T, marks, times, n-1);
else return Math.max(marks[n-1] + naiveMaxMarks(T – times[n-1], marks, times, n – 1),
naiveMaxMarks(T, marks, times, n-1));
}

static void printDPTable(int[][] DP, int n, int T, int k){

System.out.println(“DP table after iteration: ” + k);
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= T; j++) {
System.out.print(" " + DP[i][j]);
}
System.out.println();
}
}

static int bottomUpifyMaxMarks(int T, int[] marks, int[] times, int n){
int[][] DP = new int[n + 1][T + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j j) DP[i][j] = DP[i-1][j];
else DP[i][j] = Math.max(DP[i-1][j], marks[i-1] + DP[i-1][j-times[i-1]]);
}
printDPTable(DP, n, T, i);
}

return DP[n][T];
}

public static void main(String[] args) {
int n = 4, h = 10, p = 10;
int[] marksarr = { 0, 6, 11, 2, 8 };
int[] timearr = { 0, 4, 6, 2, 7 };

System.out.println(“Maximum marks that can be scored: ” +
naiveMaxMarks(10, marksarr, timearr, marksarr.length));
System.out.println(“Maximum marks that can be scored: ” +
bottomUpifyMaxMarks(10, marksarr, timearr, marksarr.length));

}
} 0
• Arjunkumar

You have M questions and N seconds to complete a test. Each question has some points and takes some time to solve (which will be given as input). Find the maximum mark that can be scored by the student within the given time N.

Python Solution:

no_of_ques=4
#int(input(‘No of questions:\t’))
total_time=10
#int(input(‘Total time:\t’))
print(‘Enter time and marks for each question:\t’)
z1=[0, 6, 4, 2, 8]
z2=[0, 4, 6, 2, 7]

ques_array=[[0,0],[6,4],[4,6],[2,2],[8,7]] #[[1,2],[2,3],[3,5],[4,7]]
”’
for i in range(no_of_ques):
sample=[]
mark=int(input(‘mark for ques {}:’.format(i+1)))
time=int(input(‘time for ques {}:’.format(i+1)))
sample.append(mark)
sample.append(time)
ques_array.append(sample)
#print(ques_array)
”’
ques_array.sort(key=lambda x:x,reverse= True)
print(ques_array)
m=0
for i in range(0,len(ques_array)):
max_marks=ques_array[i]
max_time=ques_array[i]
for j in range(i+1,len(ques_array)):
if (max_time+ques_array[j])<=total_time:
max_time+=ques_array[j]
max_marks+=ques_array[j]
if m<max_marks:
m=max_marks

print(m) 0
• Tcs

def climbing(sc, ch):
while(len(ch)!=0):
scores = sc.copy()
scores.append(ch)
scores=list(reversed(sorted(set(scores))))
r=scores.index(ch)+1
return r
ch.pop(0)
n=int(input())
sc = []
for i in range(n):
sc.append(int(input()))
m=int(input())
ch = []
for j in range(m):
ch.append(int(input()))
result = climbing(sc, ch)
print(result) 0
• Giridhar

Save the prisoner:
T=int(input())
arr=[]
for i in range(T):
arr.append(list(map(int,input().split()[:3])))

res=[]
pos=[]
for i in arr:
if i==1:
res.append(list(range(i,i+1)))

else:
res.append(list(range(i,i+1))+list(range(1,i)))

pos.append(i)

for i,j in zip(res,pos):
print(i[(j%len(i))-1]) 0
• Abhijeet

def saveThePrisoner(a,b,c):
sum=c+(b-1)
final=sum%a
if final==0:
print(a)
else:
print(final)
n=int(input(“Enter the number of Test Cases: “))
for i in range(n):
a,b,c=[int(i) for i in input(“Enter the number of prisoners, sweets and the beginning seat in respective order: “).split()]
saveThePrisoner(a,b,c) 6