Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views34 pages

TCS Practice

Coding questions tcs pyq

Uploaded by

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

TCS Practice

Coding questions tcs pyq

Uploaded by

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

1.

Given an array Arr[ ] of N integers and a positive


integer K. The task is to cyclically rotate the array
clockwise by K.

Example 1:
5 — Value of N
{10, 20, 30, 40, 50} — Element of Arr[ ]
2 — Value of K
Output:
40 50 10 20 30

Example 2:
4 — Value of N
{10, 20, 30, 40} — Element of Arr[ ]
1 — Value of K
Output:
40 10 20 30

import java.util.*;
public class rotate {
static void reverse(int arr[], int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start++] = arr[end];
arr[end--] = temp;
}
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] Arr = new int[N];

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


Arr[i] = in.nextInt();
}
int K = in.nextInt();

if (K > N) {
K = K % N;
}
reverse(Arr, 0, N - 1);
reverse(Arr, 0, K - 1);
reverse(Arr, K, N - 1);

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


System.out.print(Arr[i] + " ");
}
}
}
2. Given two non-negative integers n1 and n2.
For example:
Suppose n1 = 11 and n2 = 15.
There is the number 11, which has repeated digits, but 12, 13,
14 and 15 have no repeated digits.
So, the output is 4.

Example 1:
Input:
11 — Value of n1
15 — Value of n2
Output:
4

Example 2:
Input:
101 — Value of n1
200 — Value of n2
Output:
72

import java.util.*;
public class checkrepeat {
public static Boolean repeat(int num) {
boolean arr[] = new boolean[10];
while (num > 0) {
if (arr[num % 10] == true) {
return false;
}
arr[num % 10] = true;
num = num / 10;
}
return true;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n1 = in.nextInt();
int n2 = in.nextInt();
int count = 0;
for (int i = n1; i <= n2; i++) {
if (repeat(i) == true) {
count++;
}
}
System.out.print(count);
}
}
3. In this 3 Palindrome problem, given an input string word,
split the string into exactly 3 palindromic substrings.
Working from left to right, choose the smallest split for the
first substring that still allows the remaining word to be
split into 2 palindromes.
Similarly, choose the smallest second palindromic substring
that leaves a third palindromic substring.
If there is no way to split the word into exactly three
palindromic substrings, print “Impossible”.
Every character of the string needs to be consumed.

Cases not allowed:


- Any character of the original string remains unconsumed.
- Characters are shared between palindromic substrings.

Constraints:
1 <= length of input string <= 1000

Input:
First line contains the input string consisting of characters
between [a-z].

Output:
Print 3 substrings, one on each line.

Time Limit:
1 second

Example 1:
Input:
nayannamantenet
Output:
nayan
naman
tenet

Example 2:
Input:
aaaaa
Output:
a
a
aaa
import java.util.*;
public class palindrome {
public static Boolean checkpal(String s) {
if (s.length() == 1) return true;
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - i - 1))
return false;
}
return true;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
String s = in.nextLine();
int flag = 1, len = s.length();

for (int i = 1; i < len - 1; i++) {


String s1 = s.substring(0, i);
if (checkpal(s1)) {
for (int j = i + 1; j < len; j++) {
String s2 = s.substring(i, j);
String s3 = s.substring(j);
if (checkpal(s2) && checkpal(s3)) {
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
flag = 0;
break;
}
}
}
if (flag == 0) break;
}

if (flag == 1) System.out.println("Impossible");
}
}
4. In this Even-Odd problem, given a range [low, high] (both
inclusive), select K numbers from the range
(a number can be chosen multiple times) such that the sum of
those K numbers is even.
Calculate the number of all such permutations.
As this number can be large, print it modulo (1e9 + 7).

Constraints:
0 <= low <= high <= 10^9
K <= 10^6

Input:
First line contains two space-separated integers denoting low
and high respectively.
Second line contains a single integer K.

Output:
Print a single integer denoting the number of all such
permutations.

Time Limit:
1 second

Example 1:
Input:
4 5
3
Output:
4

Explanation:
There are 4 valid permutations: {4, 4, 4}, {4, 5, 5}, {5, 4,
5}, {5, 5, 4} — each summing to an even number.

Example 2:
Input:
1 10
2
Output:
50

Explanation:
There are 50 valid permutations like {1,1}, {1,3}, ...,
{10,10} which each sum to an even number.
import java.util.*;
public class permutation {
public static long mod = 1_000_000_007;

public static long modPow(long base, long exp) {


long result = 1;
base = base % mod;
while (exp > 0) {
if ((exp & 1) == 1) result = (result * base) %
mod;
base = (base * base) % mod;
exp = exp / 2;
}
return result;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
long low = in.nextLong();
long high = in.nextLong();
long K = in.nextLong();
long diff = high - low + 1;
long m, n;

if (diff % 2 == 0) {
m = diff / 2;
n = m;
} else {
if (low % 2 == 0) {
m = (diff - 1) / 2;
n = m + 1;
} else {
m = (diff + 1) / 2;
n = m - 1;
}
}

long total = modPow(m + n, K); // (m + n)^K


long alt = modPow((m - n + mod) % mod, K); // (m -
n)^K
long inverse2 = modPow(2, mod - 2); // Modular
inverse of 2
long result = ((total + alt) % mod * inverse2) % mod;
System.out.println(result);
}
}
5. Problem Statement:
A chocolate factory is packing chocolates into packets. The
chocolate packets are represented as an array of N integers.
The task is to find all empty packets (represented by 0) and
move them to the end of the array, maintaining the order of
the non-empty packets.

Input:
First line contains the integer N — the number of packets.
Next N lines contain the elements of the array (one element
per line).

Output:
Print the modified array with all 0s pushed to the end.

Example 1:
Input:
8
4
5
0
1
9
0
5
0

Output:
4 5 1 9 5 0 0 0

Example 2:
Input:
6
6
0
1
8
0
2

Output:
6 1 8 2 0 0
import java.util.*;
public class chocolate {
public static void emptyshift(int arr[], int n) {
int count = 0, num = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
count++;
} else {
arr[num] = arr[i];
num++;
}
}
for (int i = n - count; i < n; i++) {
arr[i] = 0;
}
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
emptyshift(arr, n);
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
6. Problem Statement:
Joseph is learning digital logic for his next semester. He got
this tricky assignment problem:
"A positive integer is given as input. Convert it to binary
and toggle all bits after the most significant bit (including
the MSB).
Then print the positive integer result after toggling."

Constraints:
1 <= N <= 100

Input:
A single integer N.

Output:
The result as an integer after toggling all bits (including
MSB).

Example 1:
Input:
10

Output:
5

Explanation:
Binary of 10 is 1010. Toggling gives 0101, which is 5.

import java.util.*;
public class decitobin {
public static String bit(int n) {
String res = "";
while (n > 0) {
int r = n % 2;
if (r == 0) {
res = "1" + res;
} else {
res = "0" + res;
}
n = n / 2;
}
return res;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(bit(n));
}
}

7. Problem Statement:
Jack is always excited about Sunday. It’s his favourite day
when he gets to play all day and go cycling with his friends.

Every time a month starts, he counts the number of Sundays he


will get to enjoy, given the starting day of the month
and the number of days in the month.

Input:
- A string denoting the day on which the month starts (e.g.,
"mon", "tue", ..., "sun").
- An integer denoting the number of days in the month.

Output:
- An integer representing the number of Sundays that fall
within those days.

Constraints:
- The day string will be in lowercase (or mixed case), e.g.,
"mon", "Sun".
- 1 ≤ number of days ≤ 1000

Example 1:
Input:
mon
13

Output:
1

Explanation:
The month starts on Monday. The first Sunday comes after 6
days, then the next after another 7.
Within 13 days, there will be 1 Sundays.
import java.util.*;
public class sun {
public static int daynumber(String s, int n) {
String arr[] = {"mon", "tue", "wed", "thurs", "fri",
"sat", "sun"};
int count = 0, idx = 0;

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


if (arr[i].equalsIgnoreCase(s)) {
idx = i;
break;
}
}

int firstSunday = (7 - idx) % 7;


if (firstSunday == 0) firstSunday = 7;

for (int i = firstSunday; i <= n; i += 7) {


count++;
}

return count;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
String day = in.nextLine();
int n = in.nextInt();
System.out.println(daynumber(day, n));
}
}
8. Problem Statement:
Airport security officials have confiscated several items at
the security checkpoint. All items are dumped into a box
represented by an array.
Each item has a certain risk level: 0 (low), 1 (medium), or 2
(high). The task is to sort the items based on their risk
levels.

Input:
First line: Integer N — number of items
Next N lines: Integer values representing risk levels (0, 1,
or 2)

Output:
Sorted array of risk levels (from lowest to highest)

Example 1:
Input:
7
1
0
2
0
1
0
2

Output:
0 0 0 1 1 2 2

Example 2:
Input:
10
2
1
0
2
1
0
0
1
2
0

Output:
0 0 0 0 1 1 1 2 2 2

Explanation:
The array is sorted by counting the frequency of 0s, 1s, and
2s, and then rebuilding the array in sorted order.

import java.util.*;
public class risk {
public static void riskcalc(int arr[], int n) {
int count0 = 0, count1 = 0, count2 = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0) count0++;
else if (arr[i] == 1) count1++;
else count2++;
}

int idx = 0;
while (count0-- > 0) arr[idx++] = 0;
while (count1-- > 0) arr[idx++] = 1;
while (count2-- > 0) arr[idx++] = 2;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
riskcalc(arr, n);
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
9. Problem Statement:
Given an integer array Arr of size N, find the count of
elements whose value is greater than all of its previous
elements.
Note: The 1st element should always be included in the count.

Input:
- First line: Integer N (size of array)
- Next N lines: Elements of array Arr[0] to Arr[N-1]

Output:
- An integer count of elements greater than all previous
elements.

Example 1:
Input:
5
7
4
8
2
9

Output:
3

Explanation:
Elements 7, 8, and 9 are greater than all their preceding
elements.

Example 2:
Input:
5
3
4
5
8
9

Output:
5

Constraints:
1 <= N <= 20
1 <= Arr[i] <= 10000

import java.util.*;
public class greaternum {
public static int greater(int arr[], int n) {
int max = arr[0], count = 1;
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
count++;
}
}
return count;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
System.out.println(greater(arr, n));
}
}
10. Problem Statement:
A supermarket maintains a pricing format for its products.
Each product has a value N printed on it.
The price of the item is the product (multiplication) of all
the digits in N.

Input:
- A single integer N (the printed code on the product)

Output:
- The price of the item (product of all digits in N)

Example 1:
Input:
5244

Output:
160

Explanation:
Digits of 5244 are 5, 2, 4, 4
Product = 5 × 2 × 4 × 4 = 160

import java.util.*;
public class pricecalc {
public static int price(int n) {
int res = 1;
while (n > 0) {
res *= (n % 10);
n /= 10;
}
return res;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
int N = in.nextInt();
System.out.println(price(N));
}
}

11. Problem Statement:


A furnishing company manufactures curtains in two colors: aqua
(a) and black (b). The curtain colors are given as a string
`str` of length N.
Each box contains curtains grouped into substrings of length
`L`. The task is to find the number of aqua-colored curtains
(`a`) in the box
that contains the **maximum number of 'a' characters**.

Note:
- If the last group has fewer than `L` characters, it is still
considered a valid group.
- You must divide the string into groups of length `L` and
find the group with the highest count of 'a'.

Input:
- First line: a string of only 'a' and 'b' characters (1 ≤ N ≤
50)
- Second line: an integer L (1 ≤ L ≤ 10)

Output:
- A single integer indicating the maximum number of 'a'
curtains in any group.

Example 1:
Input:
bbbaaababa
3

Output:
3

Explanation:
Groups: [bbb], [aaa], [bab], [a]
Group with most 'a's is [aaa] → Output: 3

Example 2:
Input:
abbbaabbb
5

Output:
2

Explanation:
Groups: [abbba], [abbb]
Most 'a's in a group = 2 → Output: 2

import java.util.*;
public class countmax {
public static int maxaqua(String s, int L) {
int mx = 0, count = 0;
int n = s.length();
for (int i = 0; i < n; i++) {
if (i % L == 0) {
mx = Math.max(mx, count);
count = 0;
}
if (s.charAt(i) == 'a') {
count++;
}
}
mx = Math.max(mx, count);
return mx;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
String s = in.nextLine();
int L = in.nextInt();
System.out.println(maxaqua(s, L));
}
}
12. Problem Statement:
An international round table conference is being held in
India. Presidents from various countries will attend.
The President and Prime Minister of India must always sit next
to each other.
Given the total number of members N, calculate the number of
**distinct seating arrangements** possible around the table,
considering circular permutations.

Constraints:
- 2 ≤ N ≤ 50

Input Format:
- A single integer N (total number of members including the
President and Prime Minister)

Output Format:
- A single integer representing the total number of valid
circular seating arrangements.

Example 1:
Input:
4

Output:
12

Explanation:
- President and PM must sit together → treat them as a pair →
so (N-1) members in circular arrangement.
- Arrangement = 2! × (N-1)!
- 2 × (4-1)! = 2 × 6 = 12

Example 2:
Input:
10
Output:
725760

Explanation:
- 2! × (10-1)! = 2 × 362880 = 725760

import java.util.*;
public class circulartable {
public static int arrangement(int N) {
int ans = 2; // 2! for swapping President and PM
for (int i = 1; i < N; i++) {
ans *= i; // (N - 1)!
}
return ans;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
int N = in.nextInt();
System.out.println(arrangement(N));
}
}
13. An intelligence agency is analyzing a suspicious
number pattern.
Given a number N and a repeat count R, calculate the sum of
the digits of N and repeat the summation R times.
Finally, return the **single-digit result** of the entire
process.

Note:
- If R is 0, output should be 0.
- You must reduce the sum to a single-digit number.

Input:
- First line: Integer N (0 < N ≤ 1000)
- Second line: Integer R (0 ≤ R ≤ 50)

Output:
- A single-digit integer

Example 1:
Input:
99
3

Output:
9

Explanation:
Sum of digits of 99 = 9 + 9 = 18
Repeat 3 times: 18 + 18 + 18 = 54
Reduce to single digit: 5 + 4 = 9

Example 2:
Input:
1234
2
Output:
2

Explanation:
Sum of digits of 1234 = 1 + 2 + 3 + 4 = 10
Repeat 2 times: 10 + 10 = 20
Reduce to single digit: 2 + 0 = 2

import java.util.*;
public class cisternways {
public static int sum_of_digits(int N) {
int sum = 0;
while (N > 0) {
sum += N % 10;
N /= 10;
}
return sum;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
int N = in.nextInt();
int R = in.nextInt();

if (R == 0) {
System.out.println(0);
} else {
int sum = sum_of_digits(N) * R;
while (sum >= 10) {
sum = sum_of_digits(sum);
}
System.out.println(sum);
}
}
}

14. Particulate matters (PMs) are one of the main


contributors to Delhi's pollution. To reduce pollution,
the government enforces the
Odd-Even vehicle rule:
- Vehicles with **odd last digit** in their registration
numbers are allowed on **odd dates**.
- Vehicles with **even last digit** in their registration
numbers are allowed on **even dates**.

If a vehicle violates this rule, a fine of **X Rupees** is


imposed.

You are given:


- An integer array `a[]` representing the **last digits** of
registration numbers of `N` vehicles.
- An integer `D` representing the **date**.
- An integer `X` representing the **fine amount**.

Your task is to calculate the **total fine collected** on that


day by identifying which vehicles violated the rule.
Input Format:
- First line: An integer N (number of vehicles)
- Next N lines: Each line contains a single digit (1–9)
representing the last digit of a vehicle's registration number
- Next line: An integer D (date of the month)
- Last line: An integer X (fine per violating vehicle)
Constraints:
- 0 < N ≤ 100
- 1 ≤ a[i] ≤ 9
- 1 ≤ D ≤ 30
- 100 ≤ X ≤ 5000
Output Format:
- Print a single integer: the total fine collected. If no
vehicle violated the rule, print 0.

Example 1:
Input:
4
5
2
3
7
12
200

Output:
600
Explanation:
Date = 12 (even), so only vehicles ending in even digits are
allowed.
Violating vehicles: 5, 3, 7 → Total fine = 3 × 200 = 600

Example 2:
Input:
5
2
5
1
6
8
3
300

Output:
900
Explanation:
Date = 3 (odd), so only vehicles ending in odd digits are
allowed.
Violating vehicles: 2, 6, 8 → Total fine = 3 × 300 = 900

import java.util.*;

public class finecalc {


public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] arr = new int[N];
int fine = 0;

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


arr[i] = in.nextInt();
}

int D = in.nextInt();
int X = in.nextInt();

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


if ((D % 2 == 0 && arr[i] % 2 != 0) || (D % 2 != 0
&& arr[i] % 2 == 0)) {
fine += X;
}
}

System.out.println(fine);
}
}
15. Problem Statement:
Alice and her friends are playing a game of verbal Kho-Kho.
Each of her N friends is seated on a chair, and Alice starts
by passing a paper with a digit to F[1].
Every friend passes the digit silently to the next.
If the final person (F[N]) writes the same digit as Alice’s
original, everyone gets a T-shirt.
Otherwise, Alice counts how many friends **misunderstood or
miscommunicated** the digit.

Input:
- First line: Integer N (number of friends)
- Second line: Array of N integers D (digits each friend
understood)

Output:
- An integer: number of friends who failed to enact or
understand the digit properly

Constraints:
- 1 ≤ N ≤ 1000
- 0 ≤ D[i] ≤ 9

Example 1:
Input:
3
4 4 4

Output:
0

Explanation:
Everyone passed the digit correctly.

Example 2:
Input:
5
1 2 3 2 2

Output:
4

Explanation:
Only the last two friends agreed on the digit. First 4 friends
either enacted or understood incorrectly.

import java.util.*;
public class KhoKho {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] arr = new int[N];

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


arr[i] = in.nextInt();
}

if (arr[0] == arr[N - 1]) {


System.out.println(0);
} else {
int count = 0;
for (int i = 1; i < N; i++) {
if (arr[i] != arr[i - 1]) {
if (i == 1) {
count++;
}
count++;
}
}
System.out.println(count);
}
}
}
16. Problem Statement:
Bob wants to place bets on a **continuous sequence of horses**
to increase his chance of winning.
He will get a reward of `K` units if any horse in his selected
sequence wins.
But he **wants to bet on a sequence whose total cost is less
than K**.
The goal is to **maximize the length** of such a continuous
sequence.

Input:
- First line: Two integers N (number of horses) and K (reward
amount)
- Second line: N integers representing the betting price for
each horse

Output:
- An integer denoting the maximum length of a continuous
sequence of horses such that total price < K

Constraints:
- 2 ≤ N ≤ 10⁵
- 1 ≤ K ≤ 10⁹
- 1 ≤ A[i] ≤ 10⁹

Example 1:
Input:
10 100
30 40 50 20 20 10 90 10 10 10

Output:
3

Explanation:
Sequences like [50 20 20] and [10 10 10] have a sum < 100 and
length 3. No longer valid sequences exist.

Example 2:
Input:
10 100
10 90 80 20 90 60 40 60 70 75

Output:
1

Explanation:
No two or more consecutive prices sum to less than 100. So
maximum length is 1.

import java.util.*;

public class horsebet {


public static void main(String args[]) {
Scanner in = new Scanner(System.in);

int N = in.nextInt(); // Number of horses


int K = in.nextInt(); // Reward threshold
int[] arr = new int[N];

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


arr[i] = in.nextInt(); // Betting price of each
horse
}

int max = 0, start = 0, sum = 0;

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


sum += arr[end];

while (sum >= K && start <= end) {


sum -= arr[start];
start++;
}

max = Math.max(max, end - start + 1);


}

System.out.println(max);
}
}
17. Tina was given a piece of silk cloth. There are
already a few points or coordinates mentioned on it. She
is creating something which needs an exact square shape
cloth. Help Tina to find out how many minimum points she
can add, to cut the perfect square from the given cloth.
There are already a few points marked on one cloth, Tina
has to include the most number of points from the given
points and should try to include the minimum number of
points or coordinates from her side.
Find the minimum number of coordinates to achieve the perfect
square. Also, try to get as bigger cloth as possible.
Let us try to understand it with an example:
Let’s say there are 3 points given which means N = 3. These
points are:
0 0
2 2
3 3
We can have 2 additional coordinates:
(2,0) & (0,2)
OR
(3,0) & (0,3)
Tina doesn’t want to lose a good deal here, so better if she
would go with (3,0) & (0,3). Hence 2 additional coordinates
were required to cut a perfect square from that piece of
cloth.
Hence the answer is 2.
Example 1:
Input:
5
0 0
100 100
200 200
100 0
0 100
Output:
0
Explanation:
In the above scenario, we can already make a square from the
given coordinates:
P1: (0, 0)
P2: (100, 0)
P3: (0, 100)
P4: (100, 100)
Hence no need for any additional coordinates here. So the
answer is 0.

Example 2:
Input:
3
0 0
2 2
3 3
Output:
2
Explanation:
In the above scenario, we can have 2 additional coordinates:
(2,0) & (0,2) OR (3,0) & (0,3). Tina doesn’t want to lose a
good deal here so better if she would go with (3,0), (0,3).
Hence 2 additional coordinates were required to cut a perfect
square from that piece of cloth. Hence the answer is 2.

import java.util.*;
public class coordinate {
public static int pointcalc(int points[][], int n) {
Set<String> pointset = new HashSet<>();
for (int p[] : points) {
pointset.add(p[0] + "," + p[1]);
}
int minneeded = 4;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
int x1 = points[i][0], y1 = points[i][1];
int x2 = points[j][0], y2 = points[j][1];
int dx = x2 - x1;
int dy = y2 - y1;
int[][] rotations = {{-dy, dx}, {dy, -dx}};
for (int rot[] : rotations) {
int rx = rot[0];
int ry = rot[1];
int x3 = x1 + rx;
int y3 = y1 + ry;
int x4 = x2 + rx;
int y4 = y2 + ry;
int count = 2;
if (pointset.contains(x3 + "," + y3)) count++;
if (pointset.contains(x4 + "," + y4)) count++;
int needed = 4 - count;
minneeded = Math.min(minneeded, needed);
}
}
}
return minneeded;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[][] arr = new int[N][2];
for (int i = 0; i < N; i++) {
arr[i][0] = in.nextInt();
arr[i][1] = in.nextInt();
}
System.out.println(pointcalc(arr, N));
}
}

18. Jack is a sports teacher at St. Patrick’s School. He


makes games not only to make the students fit but also
smart. So, he lined up all the N number classes of
students in his class. At each position, he has fixed a
board with an integer number printed on it. Each number
is unique and exactly in the range of N. Let us say there
are 10 students, then the boards will be printed with
numbers from 1 to 10 in a random order given by the
sequence A[ ]. As a rule, all students wear a jersey with
their numbers printed on it. So if there are students,
each will have a unique jersey number just like a
football team. Now, in the beginning, all the students
will stand as per the increasing order of their jersey
numbers, from left to right. The only difference will be
their respective board number which is placed at their
respective location. The board location is fixed and
cannot be changed. We can consider the arrangement as
below. Suppose there are students, and the board is
placed in the order of [2 3 1 5 4].
Board — 2, 3, 1, 5, 4
Student’s Jersey — 1, 2, 3, 4, 5
Now the game begins.
After every beat of the drum, each student will have to move
to that location (index) where his board is pointing to. In
the above case, student with jersey #1 is standing with board
#2, so now he will have to move to location #2. Similarly, all
the other students will do. So after the first beat of the
drum, the alignment will be:
Board — 2, 3, 1, 5, 4
This keeps going on and on until all the students are back to
the way they were at the beginning. So, after 6 beats of the
drum, all the students will be aligned the same way as before.
Given N and the order of the board of the respective
positions, find the number of beats required to bring back the
students to their original position. So, for the above case,
the answer is 6.
Example 1:
Input:
3
1 2 3
Output: 1
Explanation:
All the students will be standing in board positions:
Board — 1, 2, 3
Student’s Jersey — 1, 2, 3
After the first beat of the drum:
Jersey #1 will move to index 1.
Jersey #2 will move to index 2.
Jersey #3 will move to index 3.
Hence, they will be back in their position in just 1 beat.
So, the answer is 1.
Example 2:
Input:
5
2 3 1 5 4
Output:
6
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-1 of 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 in their positions after 6 beats. So,
the answer is 6.

import java.util.*;
public class order {
public static int ordernum(int arr[], int B[], int n) {
int count = 0;
int[] original = arr.clone();
int[] current = arr.clone();
while (true) {
count++;
int[] next = new int[n];
for (int i = 0; i < n; i++) {
next[i] = current[B[i] - 1];
}
if (Arrays.equals(next, original)) {
break;
}
current = next;
}
return count;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] arr = new int[N];
int[] B = new int[N];
for (int i = 0; i < N; i++) {
B[i] = in.nextInt();
arr[i] = i + 1;
}
System.out.println(ordernum(arr, B, N));
}
}

You might also like