TCS CodeVita Questions
TCS CodeVita Questions
Important topics
Here are some of the most asked concepts/questions in TCS CodeVita.
Have a look at them and start solving them now.
Important Topics
Segment Trees
Dijkstra, Kruskal
Coin Sum
Subset Sum
Knapsack
DFS in matrices
TCS CodeVita Questions
Here are some of the TCS CodeVita questions from previous year's
papers with detailed solutions.
Constellation
Constraints
Input
Example 1
Input
18
*.*#***#***#***.*.
*.*#*.*#.*.#******
***#***#***#****.*
Output
U#O#I#EA
Explanation
As it can be seen that the stars make the image of the alphabets U, O, I,
E, and A respectively.
Example 2
Input
12
*.*#.***#.*.
*.*#..*.#***
***#.***#*.*
Output
U#I#A
Explanation
As it can be seen that the stars make the image of the alphabet U, I,
and A.
Possible solution:
Input:
12
*.*#.***#.*.
*.*#..*.#***
***#.***#*.*
C++
#include <iostream>
using namespace std;
int main()
{
int n,x1,y1;
cin>>n;
char x[3][n];
for(int i=0;i<3;i++)
{
for(int j=0;j<n;j++)
{
cin>>x[i][j];
}
}
for(int i=0;i<n;i++)
{
if(x[0][i]=='#' && x[1][i]=='#' && x[2][i]=='#')
{
cout<<'#';
}
else if(x[0][i]=='.' && x[1][i]=='.' && x[2][i]=='.')
{}
else
{
char a,b,c,a1,b1,c1,a2,b2,c2;
x1 = i;
a = x[0][x1];
b = x[0][x1+1];
c = x[0][x1+2];
a1 = x[1][x1];
b1 = x[1][x1+1];
c1 = x[1][x1+2];
a2 = x[2][x1];
b2 = x[2][x1+1];
c2 = x[2][x1+2];
if(a=='.' && b=='*' && c=='.' && a1=='*' && b1=='*' && c1=='*' &&
a2=='*' && b2=='.' && c2=='*')
{
cout<<"A";
i = i + 2;
}
if(a=='*' && b=='*' && c=='*' && a1=='*' && b1=='*' && c1=='*' &&
a2=='*' && b2=='*' && c2=='*')
{
cout<<"E";
i = i + 2;
}
if(a=='*' && b=='*' && c=='*' && a1=='.' && b1=='*' && c1=='.' &&
a2=='*' && b2=='*' && c2=='*')
{
cout<<"I";
i = i + 2;
}
if(a=='*' && b=='*' && c=='*' && a1=='*' && b1=='.' && c1=='*' &&
a2=='*' && b2=='*' && c2=='*')
{
cout<<"O";
i = i + 2;
}
if(a=='*' && b=='.' && c=='*' && a1=='*' && b1=='.' && c1=='*' &&
a2=='*' && b2=='*' && c2=='*')
{
cout<<"U";
i = i + 2;
}
}
}
}
OUTPUT
U#I#A
Java 8
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// Your code here!
Scanner sc=new Scanner( System.in );
int n=sc.nextInt();
char gal[][] = new char [3][n];
for(int i=0;i<3;i++){
String a=sc.next();
for(int j=0;j<n;j++)
gal[i][j]=a.charAt(j);
}
for(int i=0;i<n;)
{
if(gal[0][i]=='#')//||gal[0][i+1]=='#')
{
System.out.print("#"); i++; continue;
}
if(gal[0][i]=='.' && gal[1][i]=='.' && gal[2][i]=='.')
{
i++; continue;
}
if(gal[0][i]=='.' && gal[0][i+2]=='.' && gal[2][i+1]=='.')
System.out.print("A");
else if(gal[1][i+1]=='.')
{
if(gal[0][i+1]=='.')
System.out.print("U");
else
System.out.print("O");
}
else if(gal[1][i]=='.' && gal[1][i+2]=='.')
System.out.print("I");
//else if(gal[0][i]=='#')
//System.out.print("#");
else
System.out.print("E");
i+=3;
}
// System.out.println("XXXXXXXX");
}
OUTPUT
U#I#A
Python
from collections import deque
def initialize():
q = deque()
#A
s = ""
q.append(['.', '*', '*'])
q.append(['*', '*', '.'])
q.append(['.', '*', '*'])
s = ''.join(map(str, q))
vowels[s] = 'A'
q.clear()
#E
q.append(['*', '*', '*'])
q.append(['*', '*', '*'])
q.append(['*', '*', '*'])
s = ''.join(map(str, q))
vowels[s] = 'E'
q.clear()
#I
q.append(['*', '.', '*'])
q.append(['*', '*', '*'])
q.append(['*', '.', '*'])
s = ''.join(map(str, q))
vowels[s] = 'I'
q.clear()
#O
q.append(['*', '*', '*'])
q.append(['*', '.', '*'])
q.append(['*', '*', '*'])
s = ''.join(map(str, q))
vowels[s] = 'O'
q.clear()
#U
q.append(['*', '*', '*'])
q.append(['.', '.', '*'])
q.append(['*', '*', '*'])
s = ''.join(map(str, q))
vowels[s] = 'U'
q.clear()
return vowels
vowels = {}
vowels = initialize()
n = int(input())
x = []
for i in range(n):
x.append(['.', '.', '.'])
for i in range(3):
l = []
l = list(input())
for j in range(n):
x[j][i] = l[j]
constellation = ""
star = deque()
for i in range(n):
if len(star) ==3:
s = ''.join(map(str, star))
if s in vowels:
constellation += vowels[s]
star.clear()
else:
star.popleft()
if x[i]==['#', '#', '#']:
star.clear()
constellation += '#'
continue
star.append(x[i])
if len(star)==3:
s = ''.join(map(str, star))
if s in vowels:
constellation += vowels[s]
print(constellation, end="")
OUTPUT
U#I#A
Now, consider the equivalent hours that are both prime numbers. We
have 3 such instances for a 24-hour 2-part day:
5~17
7~19
11~23
Example:
Input: 24 2
Constraints
Input
Output
Example 1
Input
36 3
Output
Explanation
2~14~X
3~15~X
11~23~X
Possible solution:
Input:
49 7
C++
#include<bits/stdc++.h>
using namespace std;
bool isprime(int n)
{
if(n==1)
return false;
for(int i=2;i<=(int)sqrt(n);i++)
{
if(n%i==0)
return false;
}
return true;
}
int main()
{
int D,P,i,j,p,t=1;
cin>>D>>P;
p=D/P;
int time[p][P];
for(i=0;i<P;i++)
{
for(j=0;j<p;j++)
{
time[j][i]=t++;
}
}
t=0;
for(i=0;i<p;i++)
{
bool flag=true;
for(j=0;j<P;j++)
{
if(!isprime(time[i][j]))
{
flag=false;
break;
}
}
if(flag)
t++;
}
cout<<t;
}
OUTPUT
0
Java 8
import java.util.*;
public class Main {
public static boolean isprime(int n)
{
if(n==1) return false;
for(int i=2;i<=(int) Math.sqrt(n) ; i++){
if(n%i==0)
return false;
}
return true;
}
public static void main(String[] args) throws Exception {
// Your code here!
Scanner sc= new Scanner(System.in);
// System.out.println("XXXXXXXX");
int i,j,D,P,p,t=1;
D=sc.nextInt();
P=sc.nextInt();
p=D/P;
int time[][] = new int [p][P];
for(i=0;i<P;i++){
for(j=0;j<p;j++){
time[j][i]=t++;
}
}
t=0;
for(i=0;i<p;i++)
{
boolean flag=true;
for(j=0;j<P;j++)
{
if(!isprime(time[i][j]))
{
flag=false; break;
}
}
if(flag) t++;
}
System.out.println(t);
}
}
OUTPUT
0
Python
primes = set()
def generate(lim):
for i in range(2, lim):
x=1
for j in primes:
if (i%j==0):
x=0
break
if x==1:
primes.add(i)
d, p = map(int, input().split())
generate(d)
c=0
inv = d//p
for i in range(inv):
if i in primes:
x=1
for j in range(1, p):
if (j*inv+i) not in primes:
x=0
break
if x==1:
c+=1
print(c)
OUTPUT
0
Minimum Gifts
A Company has decided to give some gifts to all of its employees. For
that, the company has given some rank to each employee. Based on
that rank, the company has made certain rules to distribute the gifts.
Constraints
1 < T < 10
Input
Output
For each test case print the number of minimum gifts required on a
new line.
Example 1
Input
12152
12
Output
Explanation
Possible solution:
Input:
12152
12
C++
#include<bits/stdc++.h>
using namespace std;
long long arr[100010];
long long brr[100010];
int main()
{
int test_case;
cin >> test_case;
for(int i = 1; i <= test_case; i++)
{
int n;
long long gift = 0, temp = 0;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> arr[i];
}
brr[0] = 1;
for(int i = 1; i < n; i++)
{
if(arr[i] > arr[i-1])
{
brr[i] = brr[i-1] + 1;
}
else
{
brr[i] = 1;
}
}
gift = brr[n-1];
for(int i = n-2; i >= 0; i--)
{
if(arr[i] > arr[i+1])
{
temp = brr[i+1] + 1;
}
else
temp = 1;
gift = gift + max(temp, brr[i]);
brr[i] = temp;
}
cout << gift << endl;
}
return 0 ;
}
Output
7
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- > 0) {
int n = sc.nextInt();
int[] ar = new int[n];
for (int i = 0; i < n; i++)
ar[i] = sc.nextInt();
int[] gifts = new int[n];
gifts[0] = 1;
// Left to Right Neighbors
for (int i = 1; i < n; i++) {
if (ar[i] > ar[i - 1])
gifts[i] = gifts[i - 1] + 1;
else
gifts[i] = 1;
}
// Right to Left Neighbors
for (int i = n - 2; i >= 0; i--) {
if (ar[i] > ar[i + 1] && gifts[i] <= gifts[i + 1])
gifts[i] = gifts[i + 1] + 1;
}
long total = 0;
for (int gift : gifts)
total += gift;
System.out.println(total);
}
}
}
Output
7
t = int(input())
while t>0:
n = int(input())
a = list(map(int, input().split()))
gifts = [1]
#gifts.append(1)
for i in range(1, n):
if a[i] > a[i-1]:
gifts.append(gifts[i-1]+1)
else:
gifts.append(1)
for i in range(n-2,-1,-1):
if a[i]>a[i+1]:
gifts[i] = max (1 + gifts[i+1], gifts[i])
g=0
for i in range(n):
g += gifts[i]
print(g)
t-=1
Output
7
Constraints
Input
First line contains two integers N and K representing size of array and
maximum numbers of operations that can be performed on the array
respectively.
Output
Print a single integer denoting the minimum sum of the final array.
Input
43
20 7 5 4
Output
17
Explanation
Sum = 17.
Possible Solution
Input:
43
20 7 5 4
Output
17
C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
long int n,k,temp,sum=0;
cin>>n;
cin>>k;
vector<int> v;
for(int i=0;i<n;i++)
{
cin>>temp;
sum=sum + temp;
v.push_back(temp);
}
make_heap(v.begin(),v.end());
long int maxi = 0,res = 0;
for(int i=0;i<k;i++)
{
maxi=v.front();
sum-=maxi;
pop_heap(v.begin(), v.end());
v.pop_back();
res = maxi / 2;
sum+=res;
v.push_back(res);
push_heap(v.begin(),v.end());
}
cout<<sum;
}
Java 8
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// Your code here!
Scanner sc= new Scanner(System.in);
// System.out.println("XXXXXXXX")
int n,k,i,s=0;
n=sc.nextInt();
k=sc.nextInt();
int a[]= new int [n];
for(i=0;i<n;i++) a[i]=sc.nextInt();
while(k-- > 0)
{
int mx=0,p=0;
for(i=0;i<n;i++){
if(a[i]>mx) {
mx=a[i];
p=i;
}
}
a[p]=a[p]/2;
}
for(i=0;i<n;i++) s+=a[i];
System.out.println(s);
}
}
Python
n, k = map(int, input().split())
frequency = []
for i in range(100000):
frequency.append(0)
sum = 0
a = list(map(int, input().split()))
for i in range(n):
frequency[a[i]] += 1
j = 100000-1
while j>0 and k>0:
while frequency[j]!=0 and k>0:
k -= 1
frequency[j] -=1
frequency[j//2] += 1
j-=1
for i in range(100000):
sum += i*frequency[i]
print(sum)
TCS CodeVita Questions #Q5
Railway Station
Note -
If Train A's departure time is x and Train B's arrival time is x, then we
can't accommodate Train B on the same platform as Train A.
Constraints
Input
Next N line contain 2 integers, a and b, denoting the arrival time and
stoppage time of train.
Output
Single integer denoting the minimum numbers of platforms needed to
accommodate every train.
Example 1
Input
10 2
5 10
13 5
Output
Explanation
Example 2
Input
2
24
62
Output
Explanation
Possible Solution
C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n],b[n];
for(int i=0;i<n;i++)
{
cin>>a[i]>>b[i];
b[i]=a[i]+b[i];
}
sort(a,a+n);
sort(b,b+n);
int p=1,r=1,i=1,j=0;
while(i<n && j<n)
{
if(a[i]<=b[j])
{
p++;
i++;
}
else if(a[i]>b[j])
{
p--;
j++;
}
if(p>r)
r=p;
}
cout<<r;
}
Java 8
import java.util.Arrays;
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[] dep = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
int stoppage = sc.nextInt();
dep[i] = arr[i] + stoppage;
}
Arrays.sort(arr);
Arrays.sort(dep);
int i = 1, j = 0, currPlatforms = 1, ans = 1;
while (i < n && j < n) {
if (arr[i] <= dep[j]) {
i++;
currPlatforms++;
}
else {
currPlatforms--;
j++;
}
ans = Math.max(ans, currPlatforms);
}
System.out.println(ans);
}
}
Python 3
n = int(input())
arr = []
dep = []
for i in range(n):
a, d = map(int, input().split())
d += a
arr.append(a)
dep.append(d)
arr.sort()
dep.sort()
i=1
j=0
plf = 1
maxplf = 1
while i<n and j<n:
if arr[i] <= dep[j]:
i+=1
plf+=1
maxplf = max ( maxplf, plf )
continue
j+=1
plf-=1
print(maxplf)
Count Pairs
Constraints
1 <= N <= 10^5
Input
First line contains two integers N and K where N is size of the array
and K is a number as described above. Second line contains N integers
separated by space.
Output
Example 1
Input
63
5 5 7 9 15 2
Output
Explanation
Other than number 15, everyone has at least 1 element in the range
[X-3, X+3]. Hence they are all happy elements. Since these five are in
number, the output is 5.
Example 2
Input
32
135
Output
Explanation
All numbers have at least 1 element in the range [X-2, X+2]. Hence
they are all happy elements. Since these three are in number, the
output is 3.
Possible Solution
Input:
32
135
C++
#include <bits/stdc++.h>
using namespace std;
int pairs(int elementlst[],int n,int z){
int count=0;
for(int i=0;i<n;i++){
int a=elementlst[i];
int id1=i;
int id2=i;
if(i==0){
while(elementlst[id2+1]==a)
id2+=1;
if(elementlst[id2+1]<=a+z && elementlst[id2+1]>=a-z)
count+=1;
}
else if(i<n-1){
while(elementlst[id2+1]==a)
id2+=1;
while(elementlst[id1-1]==a)
id1-=1;
if(((elementlst[id1-1]<=a+z) && (elementlst[id1-1]>=a-z)) || ((elementlst[id2+1]<=a+z)
&& (elementlst[id2+1]>=a-z)))
count+=1;
}
else{
while(elementlst[id1-1]==a)
id1-=1;
if(elementlst[id1-1]<=a+z && elementlst[id1-1]>=a-z)
count+=1;
}
}
return count;
}
int main() {
int n,z;
cin>>n>>z;
int elementlst[n];
for(int i=0;i<n;i++){
cin>>elementlst[i];
}
sort(elementlst,elementlst+n);
cout<<pairs(elementlst,n,z);
return 0;
}
Java 8
import java.util.*;
public class Main {
public static int pairs(int a[], int n , int z)
{
int c=0,i;
for(i=0;i<n;i++)
{
int aa=a[i];
int id1=i; int id2=i;
if(i==0)
{
while(a[id2+1]==aa)
id2++;
if(a[id2+1]<=aa+z && a[id2+1]>=aa-z)
c++;
}
else if(i<n-1)
{
while(a[id2+1]==aa)
id2+=1;
while(a[id1-1]==aa)
id1-=1;
if(((a[id1-1]<=aa+z) && (a[id1-1]>=aa-z)) || (
(a[id2+1]<=aa+z) && (a[id2+1]>=aa-z)))
c+=1;
}
else
{
while(a[id1-1]==aa)
id1-=1;
if(a[id1-1]<=aa+z && a[id1-1]>=aa-z)
c+=1;
}
}
return c;
}
public static void main(String[] args) throws Exception {
// Your code here!
Scanner sc= new Scanner(System.in);
// System.out.println("XXXXXXXX")
int n,k,i,s=0;
n=sc.nextInt();
k=sc.nextInt();
int a[]= new int [n];
for(i=0;i<n;i++) a[i]=sc.nextInt();
Arrays.sort(a);
System.out.print(pairs(a,n,k));
}
}
Python 3
n, k = map(int, input().split())
a = set()
a = set(map(int, input().split()))
a = list(a)
if n==1:
print("0")
else:
a = sorted(a)
c=0
for i in range(1, len(a)-1):
if a[i]-a[i-1]>k and a[i+1]-a[i]>k :
c += 1
if a[1]-a[0]>k:
c+=1
if a[len(a)-1]-a[len(a)-2]>k:
c +=1
print(n-c)
Critical Planets
Constraints
M <= 10000
N <= 7000
Input
Output
C lines containing one integer representing the critical planet that they
need to save in ascending order of the planet number if no planet is
critical then print -1
Time Limit
1
Example 1
Input
34
01
12
23
Output
Explanation
Since all the planets are connected with one path and cannot be
accessed by any alternative paths hence all the planets are critical.
Example 2
Input
76
02
01
12
23
45
34
35
Output
Explanation
If the republic loose the path between 2 and 3 then the two system of
planets will not be able to communicate with each other. Hence 2 and
3 are critical planets.
Possible Solution:
C++
#include <bits/stdc++.h>
typedef long long int lli;
#define pb push_back
using namespace std;
vector<int> adj[100001];
int visited[100001] , in[100001] ,low[100001];
int timer;
set<int> s;
void dfs(int node , int pre)
{
visited[node] = 1;
in[node] = low[node] = timer;
timer++;
for(int i : adj[node])
{
if(i == pre)
continue;
if(visited[i] == 1)
{
low[node] = min(low[node] , in[i]);
}
else
{
dfs(i , node);
if(low[i] > in[node])
s.insert(node) , s.insert(i);
low[node] = min(low[node] , low[i]);
}
}
}
int main()
{
int edge, vertex , a , b;
cin >> edge >> vertex;
for(int i = 0;i < edge;i++)
{
cin >> a >> b;
adj[a].pb(b);
adj[b].pb(a);
}
dfs(0 , -1);
for(int i : s)
cout << i << endl;
return 0;
}
Java 8
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.TreeSet;
public class Main {
static List<List<Integer>> graph;
static TreeSet<Integer> criticalPlanets;
static boolean[] visited;
static int[] inTime;
static int[] low;
static int timer = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
graph = new ArrayList<>(n);
for (int i = 0; i < n; i++)
graph.add(new ArrayList<>());
visited = new boolean[n];
inTime = new int[n];
low = new int[n];
criticalPlanets = new TreeSet<>();
for (int i = 0; i < m; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
graph.get(u).add(v);
graph.get(v).add(u);
}
dfs(0, -1);
for (int i : criticalPlanets)
System.out.println(i);
}
public static void dfs(int node, int parent) {
visited[node] = true;
inTime[node] = low[node] = timer++;
for (int neighbour : graph.get(node)) {
if (neighbour == parent)
continue;
if (visited[neighbour])
low[node] = Math.min(low[node], inTime[neighbour]);
else {
dfs(neighbour, node);
if (low[neighbour] > inTime[node]) {
criticalPlanets.add(neighbour);
criticalPlanets.add(node);
}
low[node] = Math.min(low[node], low[neighbour]);
}
}
}
}
Python 3
timer=0
def dfs (cur, par, timer):
vis[cur]=1
if cur!=0:
low[cur] = trav[cur] = trav[par] + 1
timer += 1
for i in g[cur]:
if i == par:
continue
if vis[i]==1:
low[cur] = min ( low[cur], trav[i] )
else:
dfs(i, cur, timer)
if low[i]>low[cur]:
defend.add(i)
defend.add(cur)
low[cur] = min (low[cur], low[i])
e, n = map(int, input().split())
g = []
vis = []
low = []
trav = []
for i in range(n):
l = []
vis.append(0)
low.append(0)
trav.append(0)
g.append(l)
for i in range(e):
a, b = map(int, input().split())
g[a].append(b)
g[b].append(a)
defend = set()
dfs(0, -1, timer)
defend = list(defend)
defend.sort()
for i in defend:
print(i)
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
#include <stdio.h>
int prime(int b)
{
int j,cnt;
cnt=1;
for(j=2;j<=b/2;j++)
{
if(b%j==0)
cnt=0;
}
if(cnt==0)
return 1;
elsereturn 0;
}
int main() {
int i,j,n,cnt,a[25],c,sum=0,count=0,k=0;
scanf("%d",&n);
for(i=2;i<=n;i++)
{
cnt=1;
for(j=2;j<=n/2;j++)
{
if(i%j==0)
cnt=0;
}
if(cnt==1)
{
a[k]=i;
k++;
}
}
for(i=0;i<k;i++)
{
sum=sum+a[i];
c= prime(sum);
if(c==1)
count++;
}
printf("%d",count);
return 0;
}
Output:
20
2
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.
Constraints:
1 <=T <= 50
1<= N1 <= 30
1<= N2 <= 30
Input Format:
Explanation:
Example 1
Input
10000
20
5 9.5
10 9.6
5 8.5
10 6.9
5 8.5
5 7.9
Output: Bank B
Example 2
Input
500000
26
13 9.5
3 6.9
10 5.6
14 8.5
6 7.4
6 9.6
Output: Bank A
Possible solution:
printf(“Bank A”);
else
printf(“Bank B”);
return 0;
}
Q3. Counting Rock Samples
Juan Marquinho 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
millions.
Input Format:
Output Format:
R lines where the ith line containing a single non-negative integer
indicating the number of the samples which lie in the ith range.
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,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, 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 are 1,
12 and 20 respectively. Hence the three lines of the output are 1, 12
and 20.
Possible Solution:
#include
int main() {
int a[1000],s,i,j,t,l1,l2,c=0;
scanf("%d",&s);
scanf("%d",&t);
for(i=0;i<s;i++)
scanf("%d",&a[i]);
for(i=0;i<t;i++)
{
scanf("%d %d",&l1,&l2);
for(j=0;j<s;j++)
{
if((a[j]>=l1)&&(a[j]<=l2))
c++;
}
printf("%dn ",c);
c=0;
}
return 0;
}
Example 1
• Input: 12,3
• Output: 4
Example 2
• Input: 30,9
• Output: 1
Possible Solution:
#include <stdio.h>
int main() {
int n,k,i,c=0;
scanf("%d",&n);
scanf("%d",&k);
for(i=n;i>=1;i--)
{
if((n%i)==0)
c++;
if(c==k)
{
printf("%d",i);
break;
}
}
if(c!=k)
printf("1");
return 0;
}
At a time he can pick up any two boxes for transferring and if both the
boxes say 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:
Constraints:
• 1 ?T?10
• 1 ?N? 10000
• 1 ? [Candies in each box] ? 100009
S. No Input Output
1
1 4 19
1234
1
2 5 34
1234
The explanation for sample input-output 1:
Possible Solution:
#include <stdio.h>
int main() {
int n,i,k=0,sum=0,s1=0,t,temp=0,j;
long c[100009],s[100009];
scanf("%d",&t);
for(int l=0;l<t;l++)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%ld",&c[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(c[i]>c[j])
{
temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}
sum=0;
k=0;
for(i=0;i<n;i++)
{
sum=sum+c[i];
s[k]=sum;
k++;
}
s1=0;
for(i=1;i<k;i++)
s1=s1+s[i];
printf("%dn",s1);
}
return 0;
}
Q6. Football League
Football League Table Statement : All major football leagues have big
league tables. Whenever a new match is played, the league table is
updated to show the current rankings (based on Scores, Goals For
(GF), Goals Against (GA)). Given the results of a few matches among
teams, write a program to print all the names of the teams in
ascending order (Leader at the top and Laggard at the bottom) based
on their rankings.
If Goal Difference(GD) is the same, the team with higher Goals For is
ranked ahead
If GF is same, the teams should be at the same rank but they should be
printed in case-insensitive alphabetic according to the team names.
More than 2 matches of same teams, should be considered as Invalid
Input.
A team can’t play matches against itself, hence if team names are same
for a given match, it should be considered Invalid Input
Input Format: First line of input will contain number of teams (N)
Second line contains names of the teams (Na) delimited by a
whitespace character Third line contains number of matches (M) for
which results are available Next M lines contain a match information
tuple {T1 T2 S1 S2}, where tuple is comprised of the following
information
Output Format: Team names in order of their rankings, one team per
line OR Print “Invalid Input” where appropriate.
• Match 1: Spain vs. England (3-0) (Spain gets 2 points, England gets
0)
• Match 2: England vs. France (1-1) (England gets 1 point, France gets
1)
• Match 3: Spain vs. France (0-2) (Spain gets 0 points, France gets 2)
Spain 2 3 2 1
England 2 1 4 -3
France 2 3 1 2
Italy 0 0 0 0
Germany 0 0 0 0
Since Italy and Germany are tied for points, the goal difference is
checked. Both have the same, so, Goals For is checked. Since both are
the same. Germany and Italy share the 4th rank. Since Germany
appears alphabetically before Italy, Germany should be printed before
Italy. Then the final result is: France Spain England Germany Italy
Sample:
Q7. Sorting Boxes
The parcel section of the Head Post Office is in a mess. The parcels that
need to be loaded to the vans have been lined up in a row in an
arbitrary order of weights. The Head Post Master wants them to be
sorted in the increasing order of the weights of the parcels, with one
exception.He wants the heaviest (and presumably the most valuable)
parcel kept nearest his office.
You and your friend try to sort these boxes and you decide to sort
them by interchanging two boxes at a time. Such an interchange needs
effort equal to the product of the weights of the two boxes.
Output Format: The output is one line giving the total effort taken to
get the boxes in sorted order, and the heaviest in position k.
Q8. On A Cube
• If it goes from a point to another point on the same face (say X to Y),
it goes in an arc of a circle that subtends an angle of 60 degrees at
the center of the circle
• If it goes from one point to another on a different face, it goes by the
shortest path on the surface of the cube, except that it never travels
along the bottom of the cube
Input Format: The first line gives an integer N, the total number of
points (including the starting point) the beetle visits
Output Format: One line with a number giving the total distance
traveled by the beetle accurate to two decimal places. Even if the
distance traveled is an integer, the output should have two decimal
places.
Constraints: None of the points the beetle visits is on the bottom face
(z=0) or on any of the edges of the cube (the lines where two faces
meet)
2<=N<=10
Sample Input-Output:
Input
3
1,1,10,2,1,10,0,5,9
Output
6.05
Input
3
1,1,10,2,1,10,0,1,9
Output
4.05
Problem Description
Input Format
Output Format
Constraints
0<n<1000
Sample Input:
13
Sample Output:
6132
Explanation:
Using these coins, we can form any value with in the given value and
itself, like below: Here the given value is 13
Solution in Python:
#find the number of five rupee coins#maximize possible number of coins, after leavinf out 4 rupees t
o make all possible values till 4
five = int((number-4)/5)
#find the number of one rupee coins#of the remaining value, number of one rupee coins is 1, if the v
alue is odd & it is 2 if the value is evenif((number-5*five) % 2) == 0:
one=2else:
one=1#find the number of two rupee coins#the rest of the amount will be from two rupee coins
two=(number-5*five-one)//2#print total coins, five ruppe coins, two rupee coins, one rupee coins
print(one+two+five,five,two,one)
Problem Description
The problem solvers have found a new Island for coding and named it
as Philaland. These smart people were given a task to make the
purchase of items at the Island easier by distributing various coins
with different values.
Manish has come up with a solution that if we make coins category
starting from $1 till the maximum price of the item present on Island,
then we can purchase any item easily. He added following example to
prove his point. Let's suppose the maximum price of an item is 5$ then
we can make coins of {$1, $2, $3, $4, $5} to purchase any item ranging
from $1 to $5. Now Manisha, being a keen observer suggested that we
could actually minimize the number of coins required and gave
following distribution {$1, $2, $3}. According to him, any item can be
purchased one time ranging from $1 to $5. Everyone was impressed
with both of them. Your task is to help Manisha come up with the
minimum number of denominations for any arbitrary max price in
Philaland.
Input Format
First line contains an integer T denoting the number of test cases. Next
T lines contains an integer N denoting the maximum price of the item
present on Philaland.
Output Format
For each test case print a single line denoting the minimum number of
denominations of coins required.
Constraints
1<=T<=100
1<=N<=5000
Sample Input 1:
10
Sample Output 1:
Sample Input2:
Sample Output2:
Explanation:
For test case 1, N=10.
According to Manish {$1, $2, $3,… $10} must be distributed. But as per
Manisha only {$1, $2, $3, $4} coins are enough to purchase any item
ranging from $1 to $10. Hence minimum is 4. Likewise denominations
could also be {$1, $2, $3, $5}. Hence answer is still 4.
According to Manish {$1, $2, $3, $4, $5} must be distributed. But as
per Manisha only {$1, $2, $3} coins are enough to purchase any item
ranging from $1 to $5. Hence minimum is 3. Likewise denominations
could also be {$1, $2, $4}. Hence answer is still 3.
Solution in Python: