KEMBAR78
Tcs NQT (Coding) | PDF | Integer (Computer Science) | String (Computer Science)
0% found this document useful (0 votes)
52 views113 pages

Tcs NQT (Coding)

The document outlines a series of coding problems related to various algorithms and data structures. Each problem includes a description, input/output format, and examples to illustrate the expected results. The problems cover topics such as array manipulation, binary conversion, counting occurrences, and calculating fines based on specific rules.

Uploaded by

rohiththumma03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views113 pages

Tcs NQT (Coding)

The document outlines a series of coding problems related to various algorithms and data structures. Each problem includes a description, input/output format, and examples to illustrate the expected results. The problems cover topics such as array manipulation, binary conversion, counting occurrences, and calculating fines based on specific rules.

Uploaded by

rohiththumma03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

TCS(NQT) previous coding questions

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 :

N=8 and arr = [4,5,0,1,9,0,5,0].

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.

[6,0,1,8,0,2] – Element of arr[0] to arr[N-1], While input each element is


separated by newline

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:

Binary representation of 10 is 1010. After toggling the bits(1010), will get


0101 which represents “5”. Hence output will print “5”.

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

mon-> input String denoting the start of the month.

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}

As 7 is the first element, it will consider in the result.

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.

Hence the output = 3.

Example 1:

Input

5 -> Value of N, represents size of Arr

7-> Value of Arr[0]

4 -> Value of Arr[1]


8-> Value of Arr[2]

2-> Value of Arr[3]

9-> Value of Arr[4]

Output :

Example 2:

5 -> Value of N, represents size of Arr

3 -> Value of Arr[0]

4 -> Value of Arr[1]

5 -> Value of Arr[2]

8 -> Value of Arr[3]

9 -> Value of Arr[4]

Output :

Constraints

1<=N<=20

1<=Arr[i]<=10000

Java
Python
Problem Statement 6

A supermarket maintains a pricing format for all its products. A value N is


printed on each product. When the scanner reads the value N on the item,
the product of all the digits in the value N is the price of the item. The task
here is to design the software such that given the code of any item N the
product (multiplication) of all the digits of value should be computed(price).

Example 1:

Input :

5244 -> Value of N

Output :
160 -> Price

Explanation:

From the input above

Product of the digits 5,2,4,4


5*2*4*4= 160

Hence, output is 160.

Java

Python
Problem Statement 7

A furnishing company is manufacturing a new collection of curtains. The


curtains are of two colors aqua(a) and black (b). The curtains color is
represented as a string(str) consisting of a’s and b’s of length N. Then, they
are packed (substring) into L number of curtains in each box. The box with
the maximum number of ‘aqua’ (a) color curtains is labeled. The task here
is to find the number of ‘aqua’ color curtains in the labeled box.

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:

3 -> Maximum number of a’s

Explanation:

From the input given above.

Dividing the string into sets of 3 characters each

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.

Hence, the output is 3.

Example 2:

Input :

abbbaabbb -> Value of str

5 -> Value of L

Output:

2 -> Maximum number of a’s

Explanation:

From the input given above,

Dividing the string into sets of 5 characters each.

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.

Hence, the output 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.

First input- Accept string that contains character a and b only

Second input- Accept value for N(Positive integer number)

The output format for testing

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 :

4 -> Value of N(No. of members)

Output :

12 -> Possible ways of seating the members

Explanation:

2 members should always be next to each other.

So, 2 members can be in 2!ways

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.

Hence, output is 12.

Example 2:

Input:

10 -> Value of N(No. of members)

Output :

725760 -> Possible ways of seating the members

Explanation:
2 members should always be next to each other.

So, 2 members can be in 2! ways

Rest of the members can be arranged in (10-1)! Ways. (1 is subtracted because


the previously selected two members will be considered as a single member now).

So, total possible ways 10 members can be seated around a round table is

2*362880 = 725760 ways.

Hence, output is 725760.

The input format for testing

The candidate has to write the code to accept one input

First input – Accept value of number of N(Positive integer number)

The output format for testing

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

for i in range(1, n + 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.

If the value of ‘R’ is 0, print the output as ‘0’.

Example 1:

Input :

99 -> Value of N

3 -> Value of R

Output :

9 -> Possible ways to fill the cistern.

Explanation:

Here, the number N=99

1. Sum of the digits N: 9+9 = 18


2. Repeat step 2 ‘R’ times i.e. 3 tims (9+9)+(9+9)+(9+9) = 18+18+18 =54
3. Add digits of 54 as we need a single digit 5+4

Hence , the output is 9.

Example 2:

Input :

1234 -> Value of N


2 -> Value of R

Output :

2 -> Possible ways to fill the cistern

Explanation:

Here, the number N=1234

1. Sum of the digits of N: 1+2+3+4 =10


2. Repeat step 2 ‘R’ times i.e. 2 times (1+2+3+4)+(1+2+3+4)= 10+10=20
3. Add digits of 20 as we need a single digit. 2+0=2

Hence, the output is 2.

Constraints:

0<N<=1000

0<=R<=50

The Input format for testing

The candidate has to write the code to accept 2 input(s)

First input- Accept value for N (positive integer number)

Second input: Accept value for R(Positive integer number)

The output format for testing

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

public static int sumOfDigits(int n)

int sum=0;

while(n>0)

sum+=n%10;

n=n/10;

return sum;

public static void main(String []args)

Scanner sc=new Scanner(System.in);

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.

Note : For violating the rule, vehicles would be fined as X Rs.

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

12 -> Value of D, i.e. date

200 -> Value of x i.e. fine

Output :

600 -> total fine collected

Explanation:

Date D=12 means , only an even number of vehicles are allowed.

Find will be collected from 5,3 and 7 with an amount of 200 each.

Hence, the output = 600.

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

3 -> Value of D i.e. date

300 -> Value of X i.e. fine


Output :

900 -> total fine collected

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.

Hence, the output = 900

Constraints:

● 0<N<=100
● 1<=a[i]<=9
● 1<=D <=30
● 100<=x<=5000

The input format for testing

The candidate has to write the code to accept 4 input(s).

First input – Accept for N(Positive integer) values (a[]), where each value is separated by a new
line.

Third input – Accept value for D(Positive integer)

Fourth input – Accept value for X(Positive integer )

The output format for testing

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

public static void main (String[]args)


{

Scanner sc = new Scanner (System.in);

int n = sc.nextInt ();

int arr[] = new int[n];

for (int i = 0; i < n; i++)

arr[i] = sc.nextInt ();

int d = sc.nextInt ();

int x = sc.nextInt ();

int countEven = 0, countOdd = 0;

for (int i = 0; i < n; i++)

if (arr[i] % 2 == 0)

countEven++;

else

countOdd++;

if (d % 2 != 0)

if (countEven == 0)

System.out.println ("0");

else

System.out.println (countEven * x);

else

if (countOdd == 0)
System.out.println ("0");

else

System.out.println (countOdd * x); } } }

Python:

n = int(input())

arr = list(map(int, input().split()))

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

It doesn't have equal elements appear in pairs

1122233

It contains three consecutive instances of an element.

22311

It is valid and the odd occurring element present in it is 3.

Enter only valid inputs.

Sample Input :

22311

Sample Output :

Java:

import java.util.*;

public class Main


{

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int arr[] = new int[n];

for(int i=0 ; i<n ; i++){

arr[i] = sc.nextInt();

int left=0,right=n-1,mid,pre,nxt;

if(arr[0] != arr[1]){

System.out.print(arr[0]);

else if(arr[n-1] != arr[n-2]){

System.out.print(arr[n-1]);

else{

while(left <= right){

mid = ((right-left)/2)+left;

pre = mid-1;

nxt = mid+1;

if((arr[pre] != arr[mid]) && (arr[nxt] != arr[mid])){

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])

elif a[n-1] != a[n-2]:

print(a[n-1])

else:
while left <= right:

mid = ((right-left)//2)+left

pre = mid-1

nxt = mid+1

if (a[pre] != a[mid]) and (a[nxt] != a[mid]):

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 :

Test case 1: possible subsets : (2,3,5) , (2,8) and (10)

Test Case 2: possible subsets : (1,2,3,4) , (2,3,5) and (1,4,5)

Java:

import java.io.*;

import java.util.*;

class Main {

static void printBool(int n, int len)

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();

static void printSubsetsCount(int set[], int n, int val)

{ int sum; int count = 0;

for (int i = 0; i < (1 << n); i++) {

sum = 0;

for (int j = 0; j < n; j++)

if ((i & (1 << j)) > 0) {

sum += set[j];

if (sum == val) {

count++;

if (count == 0) {

System.out.println("No subset is found");

} else {

System.out.println(count); }

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

int t = sc.nextInt();
int n,sum;

while(t>0)

n=sc.nextInt();

int set[] = new int[n];

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()

def printSubsetsCount(set, n, val):

sum = 0

count = 0

for i in range(0, 1 << n):

sum = 0

for j in range(0, n):

if (i & 1 << j) > 0:

sum += set[j]

if (sum == val):

count += 1

if (count == 0):

print("No subset is found")

else:

print(count)

t=int(input())

set = []

while t>0:

n = int(input())

set = list((map(int,input().strip().split())))[:n]

Sum = int(input())

printSubsetsCount(set, n, Sum) t = t-1


Problem Statement 13

Before the outbreak of coronavirus to the world, a meeting happened in a room in


Wuhan. A person who attended that meeting had COVID-19 and no one in the room
knew about it! So everyone started shaking hands with everyone else in the room as a
gesture of respect and after meeting unfortunately everyone got infected! Given the
fact that any two persons shake hands exactly once, Can you tell the total count of
handshakes that happened in that meeting?
Input Format :

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 :

Print the number of handshakes for each test-case in a new line.

Constraints :

1 <= T <= 1000

0 < N < 106

Sample Input :

Output :

Explanation :

Case 1 : The lonely board member shakes no hands, hence 0.

Case 2 : There are 2 board members, 1 handshake takes place.


Java

import java.util.*;

public class Main

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int t,n;

long sum;

t = sc.nextInt();

while(t > 0){

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.

B1 B2 B3 B4 – first state, before exchange of the books

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

1<= N <= 1000000

Input Format

Input contains one line with N, indicating the number of books and number of
students.

Output Format

Output the answer modulo 100000007.

Refer the sample output for formatting


Sample Input :

Sample Output :

Java
import java.util.*;

public class Main

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int mod = (int)1e8+7;

long n,a=0,b=1,c=2,d=0;

n = sc.nextLong();

if(n==1 || n==2)

System.out.println(n-1);

else{

for(int i=3 ; i<=n ; i++){

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.

2. Fake Palindrome: A string is called as a fake palindrome if any of its permutations


is a palindrome. For example, AAC is fake palindrome, but ACD is not.

3. Sub-string: A sub-string is a contiguous sequence (non-empty) of characters within


a string.

4. Two sub-strings are considered same if their starting indices and ending indices are
equal.

Input Format:

First line contains a string S

Output Format:

Print a single integer (number of fake palindrome sub-strings).

Constraints:

1 <= |S| <= 2 * 105

The string will contain only Upper case 'A' to 'Z'

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{

static void countSubString(String s)

int res = 0;

for (int i = 0; i < s.length(); i++)

int x = 0;

for (int j = i; j < s.length(); j++)

int temp = 1 << s.charAt(j) - 'a';

x ^= temp;

if ((x & (x - 1)) == 0)

res++;
}

System.out.print(res);

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

String str = sc.nextLine();

countSubString(str);

} }

Python

def countSubString(s):

res = 0

for i in range(len(s)):

x=0

for j in range(i, len(s)):

temp = 1 << ord(s[j]) - ord('a')

x ^= temp

if ((x & (x - 1)) == 0):

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;

public class CountPairsDivisibleBy2 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int evenCount = 0, oddCount = 0;

for (int i = 0; i < n; i++) {


int num = sc.nextInt();
if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}

// Counting valid pairs


int pairs = (evenCount * (evenCount - 1)) / 2 + (oddCount * (oddCount - 1)) / 2;
System.out.println(pairs);

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;

public class FactorialWithoutMulDiv {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(factorial(n));
sc.close();
}

public static int factorial(int n) {


if (n == 0 || n == 1) {
return 1;
}
int result = 1;
for (int i = 2; i <= n; i++) {
result = addRepeatedly(result, i);
}
return result;
}

// Method to add 'a' to itself 'b' times


public static int addRepeatedly(int a, int b) {
int sum = 0;
for (int i = 0; i < b; i++) {
sum += a;
}
return sum;
}
}

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

# Function to add 'a' to itself 'b' times


def add_repeatedly(a, b):
sum = 0
for _ in range(b):
sum += a
return sum
# Input
n = int(input())
print(factorial(n))

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;

public class MaxOnesRow {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] matrix = new int[rows][cols];

// Reading the matrix


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = sc.nextInt();
}
}
int maxOnes = -1;
int rowIndex = -1;

// Finding the row with maximum number of 1s


for (int i = 0; i < rows; i++) {
int countOnes = 0;
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 1) {
countOnes++;
}
}
if (countOnes > maxOnes) {
maxOnes = countOnes;
rowIndex = i;
}
}

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

for i, row in enumerate(matrix):


count_ones = row.count(1)
if count_ones > max_ones:
max_ones = count_ones
row_index = i

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

public class CharacterOccurrences {


public static int countOccurrences(String str1, String str2) {
HashMap<Character, Integer> freqMap = new HashMap<>();

// Count frequency of each character in str1


for (char c : str1.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}

int totalOccurrences = 0;

// Sum occurrences of unique characters from str2 in str1


for (char c : str2.toCharArray()) {
if (freqMap.containsKey(c)) {
totalOccurrences += freqMap.get(c);
}
}

return totalOccurrences;
}

public static void main(String[] args) throws IOException {


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
StringBuilder result = new StringBuilder();

for (int t = 0; t < T; t++) {


String str1 = br.readLine().trim();
String str2 = br.readLine().trim();
result.append(countOccurrences(str1, str2)).append("\n");
}

System.out.print(result);
}
}

Python

import sys
from collections import Counter

def count_occurrences(str1, str2):


freq = Counter(str1) # Count occurrences in str1
return sum(freq[char] for char in set(str2)) # Sum occurrences of unique characters in str2

# Fast input reading


T = int(sys.stdin.readline().strip())
results = []

for _ in range(T):
str1 = sys.stdin.readline().strip()
str2 = sys.stdin.readline().strip()
results.append(str(count_occurrences(str1, str2)))

# Print all results at once to optimize performance


sys.stdout.write("\n".join(results) + "\n")
Problem Statement 20
Good Number You are given a number N N, and your task is to determine whether it is a
"Good Number" or not. A Good Number is defined as a number that is divisible by the sum of
its own digits. If the number is divisible by the sum of its digits, it is classified as Good,
otherwise, it is classified as Bad.

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

public class GoodNumber {


public static boolean isGoodNumber(int n) {
int sum = 0, temp = n;

// Calculate the sum of digits


while (temp > 0) {
sum += temp % 10;
temp /= 10;
}

// Check divisibility
return (n % sum == 0);
}

public static void main(String[] args) throws IOException {


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
StringBuilder result = new StringBuilder();

for (int i = 0; i < T; i++) {


int N = Integer.parseInt(br.readLine().trim());
if (isGoodNumber(N)) {
result.append("Good Number\n");
} else {
result.append("Bad Number\n");
}
}
System.out.print(result);
}
}

Python

import sys

def is_good_number(n):
digit_sum = sum(int(digit) for digit in str(n))
return n % digit_sum == 0

# Fast input reading


T = int(sys.stdin.readline().strip())
results = []

for _ in range(T):
N = int(sys.stdin.readline().strip())
results.append("Good Number" if is_good_number(N) else "Bad Number")

# Fast output printing


sys.stdout.write("\n".join(results) + "\n")

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: {-1, 2, -1, 3, 0}


Output: 2
Explanation: The first number that does not repeat is : 2

Input: {9, 4, 9, 6, 7, 4}
Output: 6
Java

import java.util.*;

class GFG {

static int firstNonRepeating(int arr[], int n)


{
// Insert all array elements in hash
// table

Map<Integer, Integer> m = new HashMap<>();


for (int i = 0; i < n; i++) {
if (m.containsKey(arr[i])) {
m.put(arr[i], m.get(arr[i]) + 1);
}
else {
m.put(arr[i], 1);
}
}
// Traverse array again and return
// first element with count 1.
for (int i = 0; i < n; i++)
if (m.get(arr[i]) == 1)
return arr[i];
return -1;
}

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

from collections import defaultdict

def firstNonRepeating(arr, n):


mp = defaultdict(lambda: 0)

# Insert all array elements in hash table


for i in range(n):
mp[arr[i]] += 1

# Traverse array again and return


# first element with count 1.
for i in range(n):
if mp[arr[i]] == 1:
return arr[i]
return -1

# 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:

Input: arr[] = {10, 5, 3, 4, 3, 5, 6}


Output: 5
Explanation: 5 is the first element that repeats

Input: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}


Output: 6
Explanation: 6 is the first element that repeats

Java
import java.util.*;

class GfG {
static int firstRepeatingElement(int[] arr) {
HashSet<Integer> s = new HashSet<>();

// If an element is already present, return it


// else insert it
int minEle = Integer.MAX_VALUE;
for (int i = arr.length - 1; i >= 0; i--) {
if (s.contains(arr[i])) {
minEle = Math.min(minEle, i);
}
s.add(arr[i]);
}

// If no element repeats
return minEle == Integer.MAX_VALUE ? -1 : minEle;
}

public static void main(String[] args) {


int[] arr = {10, 5, 3, 4, 3, 5, 6};
int index = firstRepeatingElement(arr);
if (index == -1)
System.out.println("No repeating found!");
else
System.out.println("First repeating is " + arr[index]);} }
Python

import sys

def firstRepeatingElement(arr):
s = set()

# If an element is already present, return it


# else insert it
minEle = sys.maxsize
for i in range(len(arr) - 1, -1, -1):
if arr[i] in s:
minEle = min(minEle, i)
s.add(arr[i])

# 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:

Input: arr[] = {1, 2, 3, 4, 5, 6}, d = 2


Output: {3, 4, 5, 6, 1, 2}
Explanation: After first left rotation, arr[] becomes {2, 3, 4, 5, 6, 1} and after the second
rotation, arr[] becomes {3, 4, 5, 6, 1, 2}

Input: arr[] = {1, 2, 3}, d = 4


Output: {2, 3, 1}
Explanation: The array is rotated as follows:

After first left rotation, arr[] = {2, 3, 1}


After second left rotation, arr[] = {3, 1, 2}
After third left rotation, arr[] = {1, 2, 3}
After fourth left rotation, arr[] = {2, 3, 1}

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 {

// Function to rotate an array by d elements to the left


static void rotateArr(int[] arr, int d) {
int n = arr.length;

// Handle the case where d > size of array


d %= n;

// Reverse the first d elements


reverse(arr, 0, d - 1);

// Reverse the remaining n-d elements


reverse(arr, d, n - 1);

// Reverse the entire array


reverse(arr, 0, n - 1);
}

// Function to reverse a portion of the array


static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}

public static void main(String[] args) {


int[] arr = { 1, 2, 3, 4, 5, 6 };
int d = 2;

rotateArr(arr, d);

for (int i = 0; i < arr.length; i++)


System.out.print(arr[i] + " ");
}
}

Python

# Python Code to left rotate an array using Reversal Algorithm

# Function to rotate an array by d elements to the left


def rotateArr(arr, d):
n = len(arr)

# Handle the case where d > size of array


d %= n

# Reverse the first d elements


reverse(arr, 0, d - 1)

# Reverse the remaining n-d elements


reverse(arr, d, n - 1)

# Reverse the entire array


reverse(arr, 0, n - 1)

# Function to reverse a portion of the array


def reverse(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1

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:

Input: arr[] = [1, 2, 0, 3]


Output: 2
Explanation: The sum of left of index 2 is 1 + 2 = 3 and sum on right of index 2 is 3.

Input: arr[] = [1, 1, 1, 1]


Output: -1
Explanation: There is no equilibrium index in the array.

Input: arr[] = [-7, 1, 5, 2, -4, 3, 0]


Output: 3
Explanation: The sum of left of index 3 is -7 + 1 + 5 = -1 and sum on right of index 3 is -4 + 3
+ 0 = -1.

Java
import java.util.*;

class GfG {
static int equilibriumPoint(int[] arr) {
int prefSum = 0, total = 0;

// Calculate the array sum


for (int ele : arr) {
total += ele;
}

// Iterate pivot over all the elements of the array


for (int pivot = 0; pivot < arr.length; pivot++) {
int suffSum = total - prefSum - arr[pivot];
if (prefSum == suffSum) {
return pivot;
}
prefSum += arr[pivot];
}
// There is no equilibrium point
return -1;
}

public static void main(String[] args) {


int[] arr = {1, 7, 3, 6, 5, 6};

System.out.println(equilibriumPoint(arr));
}
}

Python

def equilibriumPoint(arr):
prefSum = 0
total = sum(arr)

# Iterate pivot over all the elements of the array


for pivot in range(len(arr)):
suffSum = total - prefSum - arr[pivot]
if prefSum == suffSum:
return pivot
prefSum += arr[pivot]

# There is no equilibrium point


return -1

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 :

Input: Array[] = {1, 3, 5, 7, 9}, K = 2.


Output: 7 9 1 3 5
Explanation:
After 1st rotation – {9, 1, 3, 5, 7}After 2nd rotation – {7, 9, 1, 3, 5}

Input: Array[] = {1, 2, 3, 4, 5}, K = 4.


Output: 2 3 4 5 1

Java
import java.util.*;
import java.lang.*;
import java.io.*;

class Array_Rotation
{

// Function to rightRotate array


static void RightRotate(int a[],
int n, int k)
{

// If rotation is greater
// than size of array
k=k%n;

for(int i = 0; i < n; i++)


{
if(i<k)
{
// Printing rightmost
// kth elements
System.out.print(a[n + i - k]
+ " ");
}
else
{
// Prints array after
// 'k' elements
System.out.print(a[i - k]
+ " ");
}
}
System.out.println();
}

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

def RightRotate(a, n, k):

# If rotation is greater
# than size of array
k = k % n;

for i in range(0, n):

if(i < k):

# Printing rightmost
# kth elements
print(a[n + i - k], end = " ");

else:

# Prints array after


# 'k' elements
print(a[i - k], end = " ");

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:

Input: a[] = [11, 1, 13, 21, 3, 7], b[] = [11, 3, 7, 1]


Output: true

Input: a[]= [1, 2, 3, 4, 5, 6], b = [1, 2, 4]


Output: true

Input: a[] = [10, 5, 2, 23, 19], b = [19, 5, 3]


Output: false

Java

import java.util.HashSet;
import java.util.Set;

class GfG {

static boolean isSubset(int[] a,int[] b) {


// Create a hash set and insert all elements of a
Set<Integer> hashSet = new HashSet<>();
for (int num : a) {
hashSet.add(num);
}

// Check each element of b in the hash set


for (int num : b) {
if (!hashSet.contains(num)) {
return false;
}
}

// If all elements of b are found in the hash set


return true;
}

public static void main(String[] args){


int[] a = { 11, 1, 13, 21, 3, 7 };
int[] b = { 11, 3, 7, 1 };
if (isSubset(a, b)) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
}

Python

def isSubset(a, b):

# Create a hash set and insert all elements of arr1


hash_set = set(a)

# Check each element of arr2 in the hash set


for num in b:
if num not in hash_set:
return False

# If all elements of arr2 are found in the hash set


return True

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

Ayush is working on a strange algorithm where he wants to convert a string from A


to B, both the strings of equal length N

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

• String A and B are of equal length

• Both of them are in lower case

• Choose a subset X from the string A, between the index 1 and N.

• Let ‘s’ be the letter 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

Let us try to understand it with and examples

Suppose there are 2 strings

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:

Original string [abbab]

Now we have chosen a subset S, let say we have taken a index 1,2,4 from A

Then the subset become [aba]

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

Next, we have to replace the smallest with all the other elements in 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]

This is exactly same as String B


Hence it is possible to convert string A to B, with 2 operations. So, the answer is 2.

Example 1:

Input:

2-> Input integer, N

de-> input string, A

cd-> Input string, B


Output:

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

4-> input integer, N

abab-> input string, A

abaa-> input string A

Output:

1 -> Output

Explanation:

Operation 1:

Now we have chosen a subset S, let 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

The input format for testing

1. First Input-Accept value of Integer, N.


2. Second Input-Accept value of string, A (Next Line)
3. Third Input-Accept value of string, B(Next Line)

The Output format for testing

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:

1. System doesn’t allow any kind of hard coded input value/values.


2. Written program code by the candidate will be verified against the inputs which are
supplied from the system.

Java
import java.util.*;

public class StringConversion {


public static int minOperationsToConvert(int n, String a, String b) {
if (a.equals(b)) {
return 0; // No operations needed if A is already equal to B
}

// Check if conversion is possible


for (int i = 0; i < n; i++) {
if (a.charAt(i) > b.charAt(i)) {
return -1; // If any character in A is lexicographically larger than B,
it's impossible
}
}

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<>();

// Find indices where A differs from B and needs to be changed


for (int i = 0; i < n; i++) {
if (aArr[i] != b.charAt(i) && b.charAt(i) == targetChar) {
indices.add(i);
}
}

if (indices.isEmpty()) {
continue;
}

// Find the smallest character in the selected subset


char smallestChar = 'z';
for (int idx : indices) {
if (aArr[idx] < smallestChar) {
smallestChar = aArr[idx];
}
}

// Replace all selected elements in A with the smallest character


for (int idx : indices) {
aArr[idx] = smallestChar;
}

operations++;

if (String.valueOf(aArr).equals(b)) {
return operations;
}
}
}

return operations;
}

private static TreeSet<Character> getSortedUniqueChars(String s) {


return new TreeSet<>(s.chars().mapToObj(c -> (char) c).toList());
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
String a = scanner.nextLine();
String b = scanner.nextLine();
scanner.close();

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

# Check if conversion is possible


if any(a[i] > b[i] for i in range(n)):
return -1 # If any character in A is lexicographically larger than B, it's impossible

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

# Find the smallest character in the subset


smallest_char = min(a[i] for i in indices)

# Replace all elements in the subset with the smallest character


a = "".join(smallest_char if i in indices else a[i] for i in range(n))
operations += 1

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<>();

// Finding cycles in the permutation


for (int i = 0; i < n; i++) {
if (!visited[i]) {
int cycleLength = 0, current = i;

while (!visited[current]) {
visited[current] = true;
current = board[current] - 1; // Move to next position
cycleLength++;
}

cycleLengths.add(cycleLength);
}
}

// Compute LCM of cycle lengths


long lcm = 1;
for (int length : cycleLengths) {
lcm = lcm(lcm, length);
}

return (int) lcm;


}

private static long lcm(long a, long b) {


return (a / gcd(a, b)) * b; // Efficient LCM formula
}

private static long gcd(long a, long b) {


return b == 0 ? a : gcd(b, a % b);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] board = new int[n];

for (int i = 0; i < n; i++) {


board[i] = sc.nextInt();
}
sc.close();

System.out.println(findMinBeats(n, board));
}
}

Python
import math

def find_min_beats(n, board):


visited = [False] * n
cycle_lengths = []

# Find all cycles in the permutation


for i in range(n):
if not visited[i]:
cycle_length = 0
current = i

while not visited[current]:


visited[current] = True
current = board[current] - 1 # Move to next index
cycle_length += 1

cycle_lengths.append(cycle_length)

# Compute LCM of all cycle lengths


lcm = 1
for length in cycle_lengths:
lcm = (lcm * length) // math.gcd(lcm, 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.*;

public class KhoKhoBeats {


public static int findBeats(int N, int[] board) {
boolean[] visited = new boolean[N];
List<Integer> cycleLengths = new ArrayList<>();

for (int i = 0; i < N; i++) {


if (!visited[i]) {
int cycleLength = 0, j = i;
while (!visited[j]) {
visited[j] = true;
j = board[j] - 1; // Move to the board position (0-based index)
cycleLength++;
}
cycleLengths.add(cycleLength);
}
}

return lcmOfList(cycleLengths);
}

private static int lcmOfList(List<Integer> nums) {


int result = nums.get(0);
for (int num : nums) {
result = lcm(result, num);
}
return result;
}

private static int lcm(int a, int b) {


return a * (b / gcd(a, b));
}

private static int gcd(int a, int b) {


return b == 0 ? a : gcd(b, a % b);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] board = new int[N];
for (int i = 0; i < N; i++) {
board[i] = scanner.nextInt();
}
scanner.close();
System.out.println(findBeats(N, board));
}
}

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

Given an array of pairs, find all symmetric pairs in it


Two pairs (a, b) and (c, d) are said to be symmetric if c is equal to b and a is equal to d. For
example, (10, 20) and (20, 10) are symmetric. Given an array of pairs find all symmetric pairs
in it.
It may be assumed that the first elements of all pairs are distinct.
Example:

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 {

// Print all pairs that have a symmetric counterpart


static void findSymPairs(int arr[][])
{
// Creates an empty hashMap hM
HashMap<Integer, Integer> hM = new HashMap<Integer,
Integer>();

// Traverse through the given array


for (int i = 0; i < arr.length; i++)
{
// First and second elements of current pair
int first = arr[i][0];
int sec = arr[i][1];

// Look for second element of this pair in hash


Integer val = hM.get(sec);

// If found and value in hash matches with first


// element of this pair, we found symmetry
if (val != null && val == first)
System.out.println("(" + sec + ", " + first + ")");

else // Else put sec element of this pair in hash


hM.put(first, sec);
}
}

// 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):

# Creates an empty hashMap hM


hM = dict()

# Traverse through the given array


for i in range(row):

# First and second elements


# of current pair
first = arr[i][0]
sec = arr[i][1]

# If found and value in hash matches with first


# element of this pair, we found symmetry
if (sec in hM.keys() and hM[sec] == first):
print("(", sec,",", first, ")")

else: # Else put sec element of


# this pair in hash
hM[first] = sec

# 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{

// Function to find the rock


// samples in the ranges
static ArrayList<Integer>findRockSample(int ranges[][],
int n, int r,
int arr[])
{
ArrayList<Integer> a = new ArrayList<>();

// Iterate over the ranges


for(int i = 0; i < r; i++)
{
int c = 0;
int l = ranges[i][0];
int h = ranges[i][1];
for(int j = 0; j < arr.length; j++)
{
if (l <= arr[j] && arr[j] <= h)
c += 1;
}
a.add(c);
}
return a;
}

// 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 } };

ArrayList<Integer> answer = new ArrayList<>();

// Function call
answer = findRockSample(ranges, n, r, arr);

for(int i = 0; i < answer.size(); i++)


System.out.print(answer.get(i) + " ");

System.out.println();
}
}

Python
def findRockSample(ranges,
n, r, arr):
a = []

# Iterate over the ranges


for i in range(r):
c = 0
l, h = ranges[i][0], ranges[i][1]
for val in arr:
if l <= val <= h:
c += 1
a.append(c)
return a
# Driver Code
if __name__ == "__main__":
n = 5
r = 2
arr = [400, 567, 890, 765, 987]
ranges = [[300, 380], [800, 1000]]

# 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:

Input: arr[] = {1, 4, 3, 2, 6, 5}


Output: {5, 6, 2, 3, 4, 1}
Explanation: The first element 1 moves to last position, the second element 4 moves to
second-last and so on.

Input: arr[] = {4, 5, 1, 2}


Output: {2, 1, 5, 4}
Explanation: The first element 4 moves to last position, the second element 5 moves to
second last and so on.

Java
import java.util.Arrays;

class GfG {

// function to reverse an array


static void reverseArray(int[] arr) {
int n = arr.length;

// Iterate over the first half and for every index i,


// swap arr[i] with arr[n - i - 1]
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
}

public static void main(String[] args) {


int[] arr = { 1, 4, 3, 2, 6, 5 };

reverseArray(arr);

for (int i = 0; i < arr.length; i++)


System.out.print(arr[i] + " ");
}
}

Python
def reverseArray(arr):
n = len(arr)

# Iterate over the first half and for every index i,


# swap arr[i] with arr[n - i - 1]
for i in range(n // 2):
temp = arr[i]
arr[i] = arr[n - i - 1]
arr[n - i - 1] = temp

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:

Input: arr[] = [1, 3, 4, 2, 6, 5, 8, 7]


Output: 4
Explanation: Sum of the elements is 1 + 3 + 4 + 2 + 6 + 5 + 8 + 7 = 36, Mean = 36/8 = 4

Input: arr[] = [4, 4, 4, 4, 4]


Output: 4
Explanation: Sum of the elements is 4 + 4 + 4 + 4 + 4 = 20, Mean = 20/5 = 4

Java
import java.util.Arrays;

class GfG {
static int findMean(int[] arr) {
int sum = 0;
for (int num : arr)
sum += num;

return sum / arr.length;


}

public static void main(String[] args) {


int[] arr = { 1, 3, 4, 2, 7, 5, 8, 6 };
System.out.println(findMean(arr));
}
}

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:

Input : welcome to geeksforgeeks


Output : wlcm t gksfrgks

Input : what is your name ?


Output : wht s yr nm ?

Java
import java.util.Scanner;

public class Practice {

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'a' || s.charAt(i) == 'e'
|| s.charAt(i) == 'i' || s.charAt(i) == 'o'
|| s.charAt(i) == 'u' || s.charAt(i) == 'A'
|| s.charAt(i) == 'E' || s.charAt(i) == 'I'
|| s.charAt(i) == 'O'
|| s.charAt(i) == 'U') {
continue;
}
else {
System.out.print(s.charAt(i));
}
}
}
}

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: “g eeks for ge eeks “


Output: “geeksforgeeks”

Input: “abc d “
Output: “abcd”

Java
class GFG
{

// Function to remove all spaces


// from a given string
static int removeSpaces(char []str)
{
// To keep track of non-space character count
int count = 0;

// Traverse the given string.


// If current character
// is not space, then place
// it at index 'count++'
for (int i = 0; i<str.length; i++)
if (str[i] != ' ')
str[count++] = str[i]; // here count is
// incremented

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):

# To keep track of non-space character count


count = 0

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:

Input: Geeks for geeks


Output: GeekS FoR GeekS

Input: Geeksforgeeks is best


Output: GeeksforgeekS IS BesT

Java
class GFG {
static String FirstAndLast(String str)
{

// Create an equivalent char array


// of given string
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {

// k stores index of first character


// and i is going to store index of last
// character.
int k = i;
while (i < ch.length && ch[i] != ' ')
i++;

// Check if the character is a small letter


// If yes, then Capitalise
ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z'
? ((int)ch[k] - 32)
: (int)ch[k]);
ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z'
? ((int)ch[i - 1] - 32)
: (int)ch[i - 1]);
}

return new String(ch);


}

// 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) :

# Create an equivalent char array


# of given string
ch = list(string);

i = 0 ;
while i < len(ch):

# k stores index of first character


# and i is going to store index of last
# character.
k = i;

while (i < len(ch) and ch[i] != ' ') :


i += 1;

# Check if the character is a small letter


# If yes, then Capitalise
if (ord(ch[k]) >= 97 and
ord(ch[k]) <= 122 ):
ch[k] = chr(ord(ch[k]) - 32);
else :
ch[k] = ch[k]

if (ord(ch[i - 1]) >= 90 and


ord(ch[i - 1]) <= 122 ):
ch[i - 1] = chr(ord(ch[i - 1]) - 32);
else :
ch[i - 1] = ch[i - 1]

i += 1
return "" . join(ch);

# Driver code
if __name__ == "__main__" :

string = "Geeks for Geeks";

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";

// Find first character from


// right which is not z.
int i = str.length() - 1;
while (str.charAt(i) == 'z' && i >= 0)
i--;

// If all characters are 'z',


// append an 'a' at the end.
if (i == -1)
str = str + 'a';

// If there are some


// non-z characters
else
str = str.substring(0, i) +
(char)((int)(str.charAt(i)) + 1) +
str.substring(i + 1);
return str;
}

// 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"

# Find first character from right


# which is not z.
i = len(s) - 1
while (s[i] == 'z' and i >= 0):
i -= 1

# If all characters are 'z', append


# an 'a' at the end.
if (i == -1):
s = s + 'a'

# If there are some non-z characters


else:
s = s.replace(s[i], chr(ord(s[i]) + 1), 1)

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:

Input : S = “ajblqcpdz”, T = “aefcnbtdi”


Output : 11
Common subsequences are : { “a”, “b”, “c”, “d”, “ab”, “bd”, “ad”, “ac”, “cd”, “abd”, “acd” }

Input : S = “a”, T = “ab”


Output : 1

Java

import java.util.*;

public class Main {

// Function to count the number of common subsequences in two


strings
public static int CommonSubsequencesCount(String s, String t) {
int n1 = s.length();
int n2 = t.length();

// To store previous computations of subproblems


int[] prev = new int[n2 + 1];

// For each character of S


for (int i = 1; i <= n1; i++) {
int[] curr = new int[n2 + 1];

// For each character in T


for (int j = 1; j <= n2; j++) {
// If characters are same in both the strings
if (s.charAt(i - 1) == t.charAt(j - 1)) {
curr[j] = 1 + curr[j - 1] + prev[j];
} else {
curr[j] = curr[j - 1] + prev[j] - prev[j - 1];
}
}
// Assigning values for further iterations
prev = curr;
}

// Return the final answer


return prev[n2];
}

// Driver program
public static void main(String[] args) {
String s = "ajblqcpdz";
String t = "aefcnbtdi";

System.out.println(CommonSubsequencesCount(s, t));
}
}
Python

def CommonSubsequencesCount(s, t):


n1 = len(s)
n2 = len(t)

# to store previous computations of subproblems


prev = [0] * (n2 + 1)

# for each character of S


for i in range(1, n1 + 1):
curr = [0] * (n2 + 1)
# for each character in T
for j in range(1, n2 + 1):
# if characters are the same in both strings
if s[i - 1] == t[j - 1]:
curr[j] = 1 + curr[j - 1] + prev[j]
else:
curr[j] = curr[j - 1] + prev[j] - prev[j - 1]
# assigning values for iteration
prev = curr

# return the final answer


return prev[n2]
# Driver Program
if __name__ == "__main__":
s = "ajblqcpdz"
t = "aefcnbtdi"
print(CommonSubsequencesCount(s, t))
Problem Statement 39
Sieve of Eratosthenes
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small
number.

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;

for (int p = 2; p * p <= n; p++) {


// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true) {
// Update all multiples of p greater than or
// equal to the square of it numbers which
// are multiple of p and are less than p^2
// are already been marked.
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++) {
if (prime[i] == true)
System.out.print(i + " ");
}
}

// 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):

# 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.
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):

# If prime[p] is not
# changed, then it is a prime
if (prime[p] == True):

# Update all multiples of p


for i in range(p * p, n+1, p):
prime[i] = False
p += 1

# Print all prime numbers


for p in range(2, n+1):
if prime[p]:
print(p)

# 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 {

// A iterative function to reverse a number


static int reverseTheNumber(int temp)
{
int ans = 0;
while (temp > 0) {
int rem = temp % 10;
ans = ans * 10 + rem;
temp = temp / 10;
}
return ans;
}

static int convert0To5(int num)


{
// if num is 0 return 5
if (num == 0)
return 5;

// Extract the last digit and


// change it if needed
else {
int temp = 0;
while (num > 0) {
int digit = num % 10;

//if digit is 0, make it 5


if (digit == 0)
digit = 5;

temp = temp * 10 + digit;


num = num / 10;
}

// call the function reverseTheNumber by passing


// temp
return reverseTheNumber(temp);
}
}

// 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;

# Extract the last digit and


# change it if needed
else:
temp = 0;

while (num > 0):


digit = num % 10;

# if digit is 0, make it 5
if (digit == 0):
digit = 5;

temp = temp * 10 + digit;


num = num // 10;

# call the function reverseTheNumber by passing


# temp
return reverseTheNumber(temp);

# Driver program
if __name__ == '__main__':
num = 10120;
print(convert0To5(num));

You might also like