Tcs NQT (Coding)
Tcs NQT (Coding)
Problem Statement 1
A chocolate factory is packing chocolates into the packets. The chocolate
packets here represent an array of N number of integer values. The task
is to find the empty packets(0) of chocolate and push it to the end of the
conveyor belt(array).
Example 1 :
There are 3 empty packets in the given set. These 3 empty packets
represented as O should be pushed towards the end of the array
Input :
8 – Value of N
[4,5,0,1,9,0,5,0] – Element of arr[O] to arr[N-1],While input each element is
separated by newline
Output:
45195000
Example 2:
Input:
6 — Value of N.
Output:
618200
Java
Python
Problem Statement 2
Joseph is learning a digital logic subject which will be for his next semester.
He usually tries to solve unit assignment problems before the lecture.
Today he got one tricky question. The problem statement is “A positive
integer has been given as an input. Convert decimal value to binary
representation. Toggle all bits of it after the most significant bit including
the most significant bit. Print the positive integer value after toggling all
bits”.
Constrains- 1<=N<=100
Example 1:
Input :
10 -> Integer
Output :
5 -> result- Integer
Explanation:
Java
Python
Problem Statement 3
Jack is always excited about sunday. It is favourite day, when he gets to
play all day. And goes to cycling with his friends.
So every time when the months starts he counts the number of sundays he
will get to enjoy. Considering the month can start with any day, be it
Sunday, Monday…. Or so on.
Count the number of Sunday jack will get within n number of days.
Example 1:
Input
13 -> input integer denoting the number of days from the start of the month.
Output :
2 -> number of days within 13 days.
Explanation:
The month start with mon(Monday). So the upcoming sunday will arrive in
next 6 days. And then next Sunday in next 7 days and so on.
Now total number of days are 13. It means 6 days to first sunday and then
remaining 7 days will end up in another sunday. Total 2 sundays may fall
within 13 days.
Java
Python
Problem Statement 4
Airport security officials have confiscated several item of the passengers at
the security check point. All the items have been dumped into a huge box
(array). Each item possesses a certain amount of risk[0,1,2]. Here, the risk
severity of the items represent an array[] of N number of integer values.
The task here is to sort the items based on their levels of risk in the array.
The risk values range from 0 to 2.
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.
Java
Python
Problem Statement 5
Given an integer array Arr of size N the task is to find the count of elements
whose value is greater than all of its prior elements.
Note : 1st element of the array should be considered in the count of the
result.
For example,
Arr[]={7,4,8,2,9}
8 and 9 are also the elements that are greater than all of its previous
elements.
Since total of 3 elements is present in the array that meets the condition.
Example 1:
Input
Output :
Example 2:
Output :
Constraints
1<=N<=20
1<=Arr[i]<=10000
Java
Python
Problem Statement 6
Example 1:
Input :
Output :
160 -> Price
Explanation:
Java
Python
Problem Statement 7
Note :
If ‘L’ is not a multiple of N, the remaining number of curtains should be
considered as a substring too. In simple words, after dividing the curtains
in sets of ‘L’, any curtains left will be another set(refer example 1)
Example 1:
Input :
Bbb aaa bab a -> Value of str
3 -> Value of L
Output:
Explanation:
Set 1: {b,b,b}
Set 2: {a,a,a}
Set 3: {b,a,b}
Set 4: {a} -> leftover characters also as taken as another set
Among all the sets, Set 2 has more number of a’s. The number of a’s in set
2 is 3.
Example 2:
Input :
5 -> Value of L
Output:
Explanation:
Set 1: {a,b,b,b,b}
Set 2: {a,a,b,b,b}
Among both the sets, set 2 has more number of a’s. The number of a’s in
set 2 is 2.
Constraints:
1<=L<=10
1<=N<=50
The input format for testing
The candidate has to write the code to accept two inputs separated by a
new line.
The output should be a positive integer number of print the message(if any)
given in the problem statement.(Check the output in Example 1, Example
2).
Java
Python
Problem Statement 8
An international round table conference will be held in india. Presidents from all
over the world representing their respective countries will be attending the
conference. The task is to find the possible number of ways(P) to make the N
members sit around the circular table such that.
The president and prime minister of India will always sit next to each other.
Example 1:
Input :
Output :
Explanation:
Rest of the members can be arranged in (4-1)! ways.(1 is subtracted because the
previously selected two members will be considered as single members now).
So total possible ways 4 members can be seated around the circular table 2*6=
12.
Example 2:
Input:
Output :
Explanation:
2 members should always be next to each other.
So, total possible ways 10 members can be seated around a round table is
The output should be a positive integer number or print the message(if any) given
in the problem statement(Check the output in example 1, example2)
Constraints :
2<=N<=50
Java
import java.math.BigInteger;
import java.util.*;
class Main
{
public static BigInteger fact(int number)
{
BigInteger res= BigInteger.ONE;
for (int i = number; i > 0; i--)
res = res.multiply(BigInteger.valueOf(i));
return res;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
BigInteger res=fact(n-1);
System.out.println(res.multiply(BigInteger.valueOf(2)));
}
}
Python
n = int(input())
fact = [0] * (n + 1)
fact[0] = 1
fact[i] = fact[i - 1] * i
print(fact[n - 1] * 2)
Problem Statement 9
An intelligence agency has received reports about some threats. The reports
consist of numbers in a mysterious method. There is a number “N” and another
number “R”. Those numbers are studied thoroughly and it is concluded that all
digits of the number ‘N’ are summed up and this action is performed ‘R’ number of
times. The resultant is also a single digit that is yet to be deciphered. The task
here is to find the single-digit sum of the given number ‘N’ by repeating the action
‘R’ number of times.
Example 1:
Input :
99 -> Value of N
3 -> Value of R
Output :
Explanation:
Example 2:
Input :
Output :
Explanation:
Constraints:
0<N<=1000
0<=R<=50
The output should be a positive integer number or print the message (if any) given
in the problem statement. (Check the output in Example 1, Example 2).
Java
import java.util.*;
class Main
int sum=0;
while(n>0)
sum+=n%10;
n=n/10;
return sum;
int n=sc.nextInt();
int r=sc.nextInt();
if(r==0)
System.out.println("0");
else
int res=sumOfDigits(n)*r;
int sum=0;
while(true)
while(res>0)
sum=sum+res%10;
res=res/10;
if((sum/10)==0)
break;
else
res=sum;
System.out.println(sum);
}}
Python:
s=input()
n=int(input())
sum=0
for i in s:
sum+=int(i)
sum*=n
s=str(sum)
while len(s)>1:
sum=0
for i in s:
sum+=int(i)
s=str(sum)
print(s)
Problem Statement 10
Particulate matters are the biggest contributors to Delhi pollution. The main reason behind the
increase in the concentration of PMs include vehicle emission by applying Odd Even concept for
all types of vehicles. The vehicles with the odd last digit in the registration number will be allowed
on roads on odd dates and those with even last digit will on even dates.
Given an integer array a[], contains the last digit of the registration number of N vehicles traveling
on date D(a positive integer). The task is to calculate the total fine collected by the traffic police
department from the vehicles violating the rules.
Example 1:
Input :
4 -> Value of N
{5,2,3,7} -> a[], Elements a[0] to a[N-1], during input each element is separated by a new line
Output :
Explanation:
Find will be collected from 5,3 and 7 with an amount of 200 each.
Example 2:
Input :
5 -> Value of N
{2,5,1,6,8} -> a[], elements a[0] to a[N-1], during input each element is separated by new line
Explanation:
Date D=3 means only odd number vehicles with are allowed.
Find will be collected from 2,6 and 8 with an amount of 300 each.
Constraints:
● 0<N<=100
● 1<=a[i]<=9
● 1<=D <=30
● 100<=x<=5000
First input – Accept for N(Positive integer) values (a[]), where each value is separated by a new
line.
The output should be a positive integer number (Check the output in Example 1, Example e) if no
fine is collected then print ”0”.
Java
import java.util.*;
class Main
if (arr[i] % 2 == 0)
countEven++;
else
countOdd++;
if (d % 2 != 0)
if (countEven == 0)
System.out.println ("0");
else
else
if (countOdd == 0)
System.out.println ("0");
else
Python:
n = int(input())
d, x = map(int, input().split())
countEven = 0
countOdd = 0
for i in range(n):
if arr[i] % 2 == 0:
countEven += 1
else:
countOdd += 1
if d % 2 != 0:
if countEven == 0:
print("0")
else:
print(countEven * x)
else:
if countOdd == 0:
print("0")
else:
print(countOdd * x)
Problem Statement 11
Given an array of integers where every element appears even number of times except one
element which appears odd number of times, write a program to find that odd occurring element in
O(log n) time. The equal elements must appear in pairs in the array but there cannot be more than
two consecutive occurrences of an element.
For example :
232
1122233
22311
Sample Input :
22311
Sample Output :
Java:
import java.util.*;
int n = sc.nextInt();
arr[i] = sc.nextInt();
int left=0,right=n-1,mid,pre,nxt;
if(arr[0] != arr[1]){
System.out.print(arr[0]);
System.out.print(arr[n-1]);
else{
mid = ((right-left)/2)+left;
pre = mid-1;
nxt = mid+1;
System.out.print(arr[mid]);
break;
}
else if(mid%2==0){
if(arr[pre] == arr[mid])
right = mid - 1;
else
left = mid + 1;
else{
if(arr[pre] == arr[mid])
left = mid + 1;
else
right = mid - 1;
} } } }
Python:
n = int(input())
a = list(map(int,input().split()))
left=0
right=n-1
if a[0] != a[1]:
print(a[0])
print(a[n-1])
else:
while left <= right:
mid = ((right-left)//2)+left
pre = mid-1
nxt = mid+1
print(a[mid])
break
elif mid%2==0 :
if a[pre] == a[mid] :
right = mid - 1
else :
left = mid + 1
else :
if a[pre] == a[mid] :
left = mid + 1
else :
right = mid - 1;
Problem Statement 12
Given an array of integers and a sum, the task is to count all subsets of given array
with sum equal to given sum.
Input :
The first line of input contains an integer T denoting the number of test cases. Then T
test cases follow. Each test case contains an integer n denoting the size of the array.
The next line contains n space separated integers forming the array. The last line
contains the sum.
Output :
Count all the subsets of given array with sum equal to given sum.
NOTE: Since result can be very large, print the value modulo 109+7.
Constraints :
1<=T<=100
1<=n<=103
1<=a[i]<=103
1<=sum<=103
Example :
Input :
2 3 5 6 8 10
10
12345
10
Output :
Explanation :
Java:
import java.io.*;
import java.util.*;
class Main {
while (n>0) {
if ((n & 1) == 1)
System.out.print(1);
else
System.out.print(0);
n >>= 1;
len--; }
while (len>0) {
System.out.print(0);
len--;
}
System.out.println();
sum = 0;
sum += set[j];
if (sum == val) {
count++;
if (count == 0) {
} else {
System.out.println(count); }
int t = sc.nextInt();
int n,sum;
while(t>0)
n=sc.nextInt();
for(int i=0;i<n;i++)
set[i] = sc.nextInt();
sum = sc.nextInt();
printSubsetsCount(set, n, sum);
t--;
} }}
Python
def printBool(n, len):
while n:
if n & 1:
print("1 ")
else:
print("0 ")
n = n >> 1
len -= 1
while len:
print("0 ")
len -= 1
print()
sum = 0
count = 0
sum = 0
sum += set[j]
if (sum == val):
count += 1
if (count == 0):
else:
print(count)
t=int(input())
set = []
while t>0:
n = int(input())
set = list((map(int,input().strip().split())))[:n]
Sum = int(input())
The first line contains the number of test cases T, T lines follow.
Each line then contains an integer N, the total number of people attended that
meeting.
Output Format :
Constraints :
Sample Input :
Output :
Explanation :
import java.util.*;
int t,n;
long sum;
t = sc.nextInt();
n = sc.nextInt();
n--;
sum = (n*(n+1))/2;
System.out.println(sum);
t--;
}}}
Python
t = int(input())
while t > 0 :
n = int(input())
n = n-1;
print((n*(n+1))//2)
t = t-1
Problem Statement 14
To enhance the book reading, the school distributed story books to students as part of
the Children’s day celebrations. To increase the reading habit, the class teacher
decided to exchange the books every week so that everyone will have a different book
to read. She wants to know how many possible exchanges are possible.
If they have 4 books and students, the possible exchanges are 9. Bi is the book of i-th
student and after the exchange, he should get a different book, other than Bi.
B2 B1 B4 B3
B2 B3 B4 B1
B2 B4 B1 B3
B3 B1 B4 B2
B3 B4 B1 B2
B3 B4 B2 B1
B4 B1 B2 B3
B4 B3 B1 B2
B4 B3 B2 B1
Find the number of possible exchanges, if the books are exchanged so that every
student will receive a different book.
Constraints
Input Format
Input contains one line with N, indicating the number of books and number of
students.
Output Format
Sample Output :
Java
import java.util.*;
long n,a=0,b=1,c=2,d=0;
n = sc.nextLong();
if(n==1 || n==2)
System.out.println(n-1);
else{
d = (c * (a + b)) % mod ;
a = b;
b = d;
c++;
}
System.out.println(d);
} } }
Python
mod = 100000007;
a=0
b=1
c=2
d=0
n = int(input())
if n==1 or n==2:
print(n-1)
else :
for i in range(1,n) :
d = (c * (a + b)) % mod
a=b
b=d
c=c+1
print(d)
Problem Statement 15
You are given a string A and you have to find the number of different sub-strings of
the string A which are fake palindromes.
Note:
1. Palindrome: A string is called a palindrome if you reverse the string yet the order of
letters remains the same. For example, MADAM.
4. Two sub-strings are considered same if their starting indices and ending indices are
equal.
Input Format:
Output Format:
Constraints:
Sample Input 1:
ABAB
Sample Output 1:
Explanation:
The fake palindrome for the string ABAB are A, B, A, B, ABA, BAB, ABAB.
Sample Input 2:
AAA
Sample output 2:
Explanation:
The fake palindrome for the string AAA are A, A, A, AA, AA, AAA
Java
import java.util.*;
class Main{
int res = 0;
int x = 0;
x ^= temp;
res++;
}
System.out.print(res);
countSubString(str);
} }
Python
def countSubString(s):
res = 0
for i in range(len(s)):
x=0
x ^= temp
res += 1
print(res);
if __name__ == '__main__':
str = input()
countSubString(str)
Problem Statement 16
Link to codechef: Count Pairs divisible by 2 Practice Problem in TCS NQT Coding Questions
Given an array of integers, count the number of pairs (i, j) where 0 ≤ i < j < n and the sum of
the elements at indices i and j is divisible by 2.
Sample 1:
Input
Output
3
4
6123
6
221753
2
48
2
7
1
Explanation:
Test Case 1: There are only two pairs formed- (6,2) and (1,3).
Test case 2: These are the 7 pairs that are formed- (2,2), (1,7), (1,5), (1,3), (7,5), (7,3), (5,3).
Test case 3: There is only one pair that is formed- (4,8).
Java
import java.util.Scanner;
sc.close();
}
}
Python
t = int(input())
while t > 0:
# Your code goes here
t -= 1
n = int(input())
arr = [int(x) for x in input().split()]
even_count = sum(1 for x in arr if x%2==0)
odd_count = n-even_count
pairs = (even_count*(even_count-1))//2 + (odd_count*(odd_count-1))//2
print(pairs)
Problem Statement 17
Calculate the factorial of a given non-negative integer nnn without using the multiplication (*)
or division (/) operators.
Example:
Input: 5
Output: 120
Link to Codechef : Factorial without Multiplication & Division Practice Problem in TCS NQT
Coding Questions
Java
import java.util.Scanner;
Python
def factorial(n):
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result = add_repeatedly(result, i)
return result
Problem Statement 18
Given a binary matrix (a matrix containing only 0s and 1s), the task is to identify the row that
contains the maximum number of 1s.
Example:
Input:
33
011
110
001
Output:
Row 1
Explanation: Row 1 has two 1s, which is more than any other row.
Java
import java.util.Scanner;
if (rowIndex != -1) {
System.out.println("Row " + rowIndex);
} else {
System.out.println("No 1s found in the matrix.");
}
sc.close();
}
}
Python
def find_max_ones_row(matrix):
max_ones = -1
row_index = -1
if row_index != -1:
print(f"Row {row_index}")
else:
print("No 1s found in the matrix.")
# Example usage
rows, cols = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(rows)]
find_max_ones_row(matrix)
Problem Statement 19
Count Character Occurrences You are given two strings, str1 and str2. Your mission is to
calculate the total number of occurrences of each unique character of str2 within the string
str1. The task is to find the sum of occurrences of all unique characters from str2 in str1 and
return this total count.
Input Format:
● The first line contains a single integer T (1≤T≤1001 \leq T \leq 1001≤T≤100) — the
number of test cases.
● For each test case:
○ The first line contains the string str1.
○ The second line contains the string str2.
Output Format:
● For each test case, print a single integer on a new line — the total sum of occurrences
of all unique characters from str2 found in str1.
Constraints:
● 1≤T≤1001 \leq T \leq 1001≤T≤100 (Number of test cases is at most 100)
● 1≤∣ str1∣ ,∣ str2∣ ≤1051 \leq |str1|, |str2| \leq 10^51≤∣ str1∣ ,∣ str2∣ ≤105 (Length of
both strings can be up to 100,000 characters)
● Both str1 and str2 consist of only lowercase English letters (a-z).
Java
import java.util.*;
import java.io.*;
int totalOccurrences = 0;
return totalOccurrences;
}
System.out.print(result);
}
}
Python
import sys
from collections import Counter
for _ in range(T):
str1 = sys.stdin.readline().strip()
str2 = sys.stdin.readline().strip()
results.append(str(count_occurrences(str1, str2)))
Input Format:
The first line of input will contain a single integer T, denoting the number of test cases.
Each test case contains a single integer N, the number you need to check.
Output Format:
For each test case, print "Good Number" if the number is a Good, otherwise print "Bad
Number".
Java
import java.io.*;
// Check divisibility
return (n % sum == 0);
}
Python
import sys
def is_good_number(n):
digit_sum = sum(int(digit) for digit in str(n))
return n % digit_sum == 0
for _ in range(T):
N = int(sys.stdin.readline().strip())
results.append("Good Number" if is_good_number(N) else "Bad Number")
Problem Statement 21
Find first non-repeating element in a given Array of integers
Given an array of integers of size N, the task is to find the first non-repeating element in this
array.
Examples:
Input: {9, 4, 9, 6, 7, 4}
Output: 6
Java
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
int arr[] = { 9, 4, 9, 6, 7, 4 };
int n = arr.length;
System.out.println(firstNonRepeating(arr, n));
}
}
Python
# Driver Code
arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
print(firstNonRepeating(arr, n))
Problem Statement 22
Find the first repeating element in an array of integers
Given an array of integers arr[], The task is to find the index of the first repeating element in it
i.e. the element that occurs more than once and whose index of the first occurrence is the
smallest.
Examples:
Java
import java.util.*;
class GfG {
static int firstRepeatingElement(int[] arr) {
HashSet<Integer> s = new HashSet<>();
// If no element repeats
return minEle == Integer.MAX_VALUE ? -1 : minEle;
}
import sys
def firstRepeatingElement(arr):
s = set()
# If no element repeats
return -1 if minEle == sys.maxsize else minEle
arr = [10, 5, 3, 4, 3, 5, 6]
index = firstRepeatingElement(arr)
if index == -1:
print("No repeating found!")
else:
print("First repeating is", arr[index])
Problem Statement 23
Given an array of integers arr[] of size n, the task is to rotate the array elements to the left by
d positions.
Examples:
Idea of implementation: The idea is to use Juggling Algorithm which is based on rotating
elements in cycles. Each cycle is independent and represents a group of elements that will
shift among themselves during the rotation. If the starting index of a cycle is i, then next
elements of the cycle can be found at indices (i + d) % n, (i + 2d) % n, (i + 3d) % n … and so
on till we return to the original index i.
So for any index i, we know that after rotation, the element that will occupy this position is
arr[(i + d) % n]. Consequently, for every index in the cycle, we will place the element that
should be in that position after the rotation is completed.
Java
// Java Code to left rotate an array using Reversal Algorithm
import java.util.Arrays;
class GfG {
rotateArr(arr, d);
Python
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6]
d=2
rotateArr(arr, d)
for i in range(len(arr)):
print(arr[i], end=" ")
Problem Statement 24
Equilibrium Index
Given an array arr[] of size n, the task is to return an equilibrium index (if any) or -1 if no
equilibrium index exists. The equilibrium index of an array is an index such that the sum of all
elements at lower indexes equals the sum of all elements at higher indexes.
Note: When the index is at the start of the array, the left sum is 0, and when it’s at the end, the
right sum is 0.
Examples:
Java
import java.util.*;
class GfG {
static int equilibriumPoint(int[] arr) {
int prefSum = 0, total = 0;
System.out.println(equilibriumPoint(arr));
}
}
Python
def equilibriumPoint(arr):
prefSum = 0
total = sum(arr)
if __name__ == "__main__":
arr = [1, 7, 3, 6, 5, 6]
result = equilibriumPoint(arr)
print(result)
Problem Statement 25
Print array after it is right rotated K times
Given an Array of size N and a value K, around which we need to right rotate the array. How
do you quickly print the right rotated array?
Examples :
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class Array_Rotation
{
// If rotation is greater
// than size of array
k=k%n;
// Driver program
public static void main(String args[])
{
int Array[] = {1, 2, 3, 4, 5};
int N = Array.length;
int K = 2;
RightRotate(Array, N, K);
}
}
Python
# If rotation is greater
# than size of array
k = k % n;
# Printing rightmost
# kth elements
print(a[n + i - k], end = " ");
else:
print("\n");
# Driver code
Array = [ 1, 2, 3, 4, 5 ];
N = len(Array);
K = 2;
RightRotate(Array, N, K);
Problem Statement 26
Check if an array is subset of another array
Given two arrays a[] and b[] of size m and n respectively, the task is to determine whether b[]
is a subset of a[]. Both arrays are not sorted, and elements are distinct.
Examples:
Java
import java.util.HashSet;
import java.util.Set;
class GfG {
Python
if __name__ == "__main__":
a = [11, 1, 13, 21, 3, 7]
b = [11, 3, 7, 1]
if isSubset(a, b):
print("true")
else:
print("false")
Problem Statement 27
• Let ‘s’ be the letter which alphabetically comes before all other letters in the subset. Let ‘s’
be called the ‘smallest element’ in the subset.
• Replace all the elements of 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
A = abcab
B = aabab
Operation 1:
Now we have chosen a subset S, let us say we have taken index 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 subset with this element. So ‘b’
with replace everything in [bcb]. which becomes [bbb].
Now we will place all the respective elements back to their respective index. This will
update the original string as [abbab]
Operation 2:
Now we have chosen a subset S, let say we have taken a index 1,2,4 from A
Next, we have to replace the smallest with all the other elements in subset. So ‘a’ will
replace everything in [aba]
Now we will place all the respective elements back to their respective index. This will
update the original string as [aabab]
Example 1:
Input:
-1
Explanation:
In the above example we can clearly 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:
Output:
1 -> Output
Explanation:
Operation 1:
Now we have chosen a subset S, let say we have taken index 3,4 from A
Then the 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 subset. So ‘a’ will replace
everything in [abl, which becomes [aa]
Now we will place all the respective elements back to their respective index. This will
update the original string as [abaa]
This is exactly same as String B
Hence it is possible to convert string A to B. with 1 operation. So, the answer is 1.
Constraints:
1. 1<=N<=1000
2. N integer
3. Only lower case letters of the English alphabet
4. Length of A,B = N
1. The output is an integer as per above logic. (Check the output in Example 1, Example 21
2. Additional messages in output will cause the failure of test cases
Instructions:
Java
import java.util.*;
int operations = 0;
char[] aArr = a.toCharArray();
while (!String.valueOf(aArr).equals(b)) {
for (char targetChar : getSortedUniqueChars(b)) { // Process
characters in increasing order
List<Integer> indices = new ArrayList<>();
if (indices.isEmpty()) {
continue;
}
operations++;
if (String.valueOf(aArr).equals(b)) {
return operations;
}
}
}
return operations;
}
System.out.println(minOperationsToConvert(n, a, b));
}
}
Python
def min_operations_to_convert(n, a, b):
if a == b:
return 0 # No operations needed if A is already equal to B
operations = 0
while a != b:
for target_char in sorted(set(b)): # Process characters in increasing order
indices = [i for i in range(n) if a[i] != b[i] and b[i] == target_char]
if not indices:
continue
if a == b:
return operations
return operations
# Input handling
n = int(input())
a = input().strip()
b = input().strip()
print(min_operations_to_convert(n, a, b))
Problem Statement 28
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 numb class. of students in his class.
At each position he has fixed a board with the Integer number printed on it. Each of the
numbers are unique and are 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 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 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 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 as board positions;
Board — 1, 2, 3
Student’s Jersey –1, 2, 3
After 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 on their own 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, 5
After 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, 4
After 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, 5
After 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, 5
After Beat-5 of the drum:
Board — 2, 3, 1, 5, 4
Student’s Jersey — 2, 3, 1, 5, 4
After Beat-6 of the drum:
Board — 2, 3, 1, 5, 4
Student’s Jersey — 1, 2, 3, 4, 5
Hence, they will be back on their positions after 6 beats. So, the answer is 6.
Constraints:
• 1<=N<=100000
• 1 <=A[i] <= N
• All A[i] will be distinct numbers
• N and. Only Integers.
The input format for testing:
• First Input – Accept value of In1101
• Next ‘N’ Lines-Elements of sequence A[]
Java
import java.util.*;
public class JerseyRearrangement {
public static int findMinBeats(int n, int[] board) {
boolean[] visited = new boolean[n];
List<Integer> cycleLengths = new ArrayList<>();
while (!visited[current]) {
visited[current] = true;
current = board[current] - 1; // Move to next position
cycleLength++;
}
cycleLengths.add(cycleLength);
}
}
System.out.println(findMinBeats(n, board));
}
}
Python
import math
cycle_lengths.append(cycle_length)
return lcm
# Input Handling
n = int(input())
board = [int(input()) for _ in range(n)]
# Output Result
print(find_min_beats(n, board))
Problem Statement 29
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 will give it to Alice
Alice will compare both the papers. If the digits are similar then, Alice will give a T-shirt to
each friend.
However, if the digits do not match then Alice will ask digits from each friend, and she will
offer the T-shirts to only the ones who understood the digits correctly.
Given N number of friends and digit array D, denoting the digit understood by each friend F.
find 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 have understood digits correctly.
Example 2:
5
12322
Output:
4
Explanation:
1st, 2nd, 3rd and 4th friends could not enact OR understand the enactment. Constraints:
• 1<=N<10000
• 0<=D[i]<=9
The input format for testing:
• First-line Contains a Positive Integer denoting N
• Next line: Contains N elements of the array space separated denoting array D.
The Output format for testing:
Output the single integer denoting how many have not enacted well OR have not understood
the enactment.
Java
import java.util.*;
return lcmOfList(cycleLengths);
}
Python
import math
from sys import stdin
def find_beats(N, board):
visited = [False] * N
cycle_lengths = []
for i in range(N):
if not visited[i]:
cycle_length, j = 0, i
while not visited[j]:
visited[j] = True
j = board[j] - 1 # Move to the board position (0-based index)
cycle_length += 1
cycle_lengths.append(cycle_length)
return math.lcm(*cycle_lengths)
if __name__ == "__main__":
N = int(input().strip())
board = list(map(int, input().strip().split()))
print(find_beats(N, board))
Problem Statement 30
Input: arr[] = {{11, 20}, {30, 40}, {5, 10}, {40, 30}, {10, 5}}
Output: Following pairs have symmetric pairs
(30, 40)
(5, 10)
Java
import java.util.HashMap;
class SymmetricPairs {
// Driver method
public static void main(String arg[])
{
int arr[][] = new int[5][2];
arr[0][0] = 11; arr[0][1] = 20;
arr[1][0] = 30; arr[1][1] = 40;
arr[2][0] = 5; arr[2][1] = 10;
arr[3][0] = 40; arr[3][1] = 30;
arr[4][0] = 10; arr[4][1] = 5;
findSymPairs(arr);
}
}
Python
def findSymPairs(arr, row):
# Driver Code
if __name__ == '__main__':
arr = [[0 for i in range(2)]
for i in range(5)]
arr[0][0], arr[0][1] = 11, 20
arr[1][0], arr[1][1] = 30, 40
arr[2][0], arr[2][1] = 5, 10
arr[3][0], arr[3][1] = 40, 30
arr[4][0], arr[4][1] = 10, 5
findSymPairs(arr, 5)
Problem Statement 31
Counting Rock Samples | TCS Codevita 2020
John is a geologist, and he needs to count rock samples in order to send it to a chemical
laboratory. He has a problem. The laboratory only accepts rock samples by a range of sizes in
ppm (parts per million). John needs your help. Your task is to develop a program to get the
number of rocks in each range accepted by the laboratory.
Problem Statement: Given an array samples[] denoting sizes of rock samples and a 2D array
ranges[], the task is to count the rock samples that are in the range ranges[i][0] to ranges[i][1],
for every possible 1 <= i <= N.
Examples:
Input: samples[] = {345, 604, 321, 433, 704, 470, 808, 718, 517, 811}, ranges[] = {{300, 380},
{400, 700}}
Output: 2 4
Explanation:
Range [300, 380]: Samples {345, 321} lie in the range. Therefore, the count is 2.
Range [400, 700]: Samples {433, 604, 517, 470} lie in the range. Therefore, the count is 4.
Input: samples[] = {400, 567, 890, 765, 987}, ranges[] = {{300, 380}, {800, 1000}
Output: 0 2
Java
// Java program of the
// above approach
import java.util.*;
import java.io.*;
class GFG{
// Driver Code
public static void main(String args[])
{
int n = 5;
int r = 2;
int arr[] = { 400, 567, 890, 765, 987 };
int ranges[][] = { { 300, 380 }, { 800, 1000 } };
// Function call
answer = findRockSample(ranges, n, r, arr);
System.out.println();
}
}
Python
def findRockSample(ranges,
n, r, arr):
a = []
# Function Call
print(*findRockSample(ranges, n, r, arr))
Problem Statement 32
Given an array arr[], the task is to reverse the array. Reversing an array means rearranging
the elements such that the first element becomes the last, the second element becomes
second last and so on.
Examples:
Java
import java.util.Arrays;
class GfG {
reverseArray(arr);
Python
def reverseArray(arr):
n = len(arr)
if __name__ == "__main__":
arr = [1, 4, 3, 2, 6, 5]
reverseArray(arr)
for i in range(len(arr)):
print(arr[i], end=" ")
Problem Statement 33
Given an array arr[]. The task is to find the mean(floor value) of the array.
Examples:
Java
import java.util.Arrays;
class GfG {
static int findMean(int[] arr) {
int sum = 0;
for (int num : arr)
sum += num;
Python
def findMean(arr):
return sum(arr) // len(arr)
if __name__ == "__main__":
arr = [1, 3, 4, 2, 7, 5, 8, 6]
print(findMean(arr))
Problem Statement 34
Given a string, remove the vowels from the string and print the string without vowels.
Examples:
Java
import java.util.Scanner;
Python
def rem_vowel(string):
vowels = ['a','e','i','o','u']
result = [letter for letter in string if letter.lower() not in vowels]
result = ''.join(result)
print(result)
# Driver program
string = "GeeksforGeeks - A Computer Science Portal for Geeks"
rem_vowel(string)
string = "Loving Python LOL"
rem_vowel(string)
Problem Statement 35
Given a string, remove all spaces from the string and return it.
Input: “abc d “
Output: “abcd”
Java
class GFG
{
return count;
}
// Driver code
public static void main(String[] args)
{
char str[] = "g eeks for ge eeks ".toCharArray();
int i = removeSpaces(str);
System.out.println(String.valueOf(str).subSequence(0, i));
}
}
Python
def removeSpaces(string):
list = []
# Traverse the given string. If current character
# is not space, then place it at index 'count++'
for i in xrange(len(string)):
if string[i] != ' ':
list.append(string[i])
return toString(list)
# Utility Function
def toString(List):
return ''.join(List)
# Driver program
string = "g eeks for ge eeks "
print removeSpaces(string)
Problem Statement 36
Given the string, the task is to capitalise the first and last character of each word in a string.
Examples:
Java
class GFG {
static String FirstAndLast(String str)
{
// Driver code
public static void main(String args[])
{
String str = "Geeks for Geeks";
System.out.println(str);
System.out.println(FirstAndLast(str));
}
}
Python
def FirstAndLast(string) :
i = 0 ;
while i < len(ch):
i += 1
return "" . join(ch);
# Driver code
if __name__ == "__main__" :
print(string);
print(FirstAndLast(string));
Problem Statement 37
Given a string, find lexicographically next string.
Examples:
Input : geeks
Output : geekt
The last character 's' is changed to 't'.
Input : raavz
Output : raawz
Since we can't increase last character,
we increment previous character.
Input : zzz
Output : zzza
Java
import java.util.*;
class GFG
{
public static String nextWord(String str)
{
// if string is empty
if (str == "")
return "a";
// Driver Code
public static void main (String[] args)
{
String str = "samez";
System.out.print(nextWord(str));
}
}
Python
def nextWord(s):
# If string is empty.
if (s == " "):
return "a"
return s
# Driver code
if __name__ == '__main__':
str = "samez"
print(nextWord(str))
Problem Statement 38
Given two string S and T. The task is to count the number of the common subsequence in S
and T.
Examples:
Java
import java.util.*;
// Driver program
public static void main(String[] args) {
String s = "ajblqcpdz";
String t = "aefcnbtdi";
System.out.println(CommonSubsequencesCount(s, t));
}
}
Python
Examples:
Input: n = 10
Output: 2 3 5 7
Explanation: The Sieve of Eratosthenes efficiently finds all prime numbers up to 10 by
marking multiples of each prime starting from 2.
Input: n = 20
Output: 2 3 5 7 11 13 17 19
Explanation: By iteratively marking multiples of primes, the sieve finds all prime numbers up to
20 efficiently.
Input: n = 30
Output: 2 3 5 7 11 13 17 19 23 29
Explanation: Using the sieve method, all primes up to 30 are found by eliminating multiples of
each prime systematically.
Java
class SieveOfEratosthenes {
void sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and
// initialize all entries it as true. A value in
// prime[i] will finally be false if i is Not a
// prime, else true.
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
// Driver Code
public static void main(String args[])
{
int n = 30;
System.out.print("Following are the prime numbers ");
System.out.println("smaller than or equal to " + n);
SieveOfEratosthenes g = new SieveOfEratosthenes();
g.sieveOfEratosthenes(n);
}
}
Python
def SieveOfEratosthenes(n):
# If prime[p] is not
# changed, then it is a prime
if (prime[p] == True):
# Driver code
if __name__ == '__main__':
n = 30
print("Following are the prime numbers smaller"),
print("than or equal to", n)
SieveOfEratosthenes(n)
Problem Statement 40
Given an integer as input and replace all the ‘0’ with ‘5’ in the integer.
Examples:
Input: 102
Output: 152
Explanation: All the digits which are '0' is replaced by '5'
Input: 1020
Output: 1525
Explanation: All the digits which are '0' is replaced by '5'
Java
import java.io.*;
class GFG {
// Driver program
public static void main(String args[])
{
int num = 10120;
System.out.println(convert0To5(num));
}
}
Python
def reverseTheNumber(temp):
ans = 0;
while (temp > 0):
rem = temp % 10;
ans = ans * 10 + rem;
temp = temp // 10;
return ans;
def convert0To5(num):
# if num is 0 return 5
if (num == 0):
return 5;
# if digit is 0, make it 5
if (digit == 0):
digit = 5;
# Driver program
if __name__ == '__main__':
num = 10120;
print(convert0To5(num));