0% found this document useful (0 votes)
2 views49 pages

Tcs Asked Coding Question

The document contains coding questions from the TCS NQT 2027 July Batch, including solutions in Java. It covers various topics such as searching for the closest element in a sorted array, prime factorization, finding the Kth best-selling product, time conversion, price comparison, postfix expression evaluation, largest rectangle in a histogram, character frequency counting, and arithmetic progression calculations. Each question includes input/output specifications, sample inputs/outputs, and explanations of the provided solutions.

Uploaded by

gpartha0673
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)
2 views49 pages

Tcs Asked Coding Question

The document contains coding questions from the TCS NQT 2027 July Batch, including solutions in Java. It covers various topics such as searching for the closest element in a sorted array, prime factorization, finding the Kth best-selling product, time conversion, price comparison, postfix expression evaluation, largest rectangle in a histogram, character frequency counting, and arithmetic progression calculations. Each question includes input/output specifications, sample inputs/outputs, and explanations of the provided solutions.

Uploaded by

gpartha0673
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

TCS ASKED CODING QUESTION

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 1 – Search Key (Closest Element)
============================================================

QUESTION
--------
Given a sorted array and a key, perform Search.

• If the key is found, print the key.


• Otherwise, print the element whose value is closest to the key.
• If two elements are equally close, print the smaller element.

INPUT
-----
• First line contains an integer N.
• Second line contains N sorted integers.
• Third line contains the integer key.

OUTPUT
------
• Print the key if found.
• Otherwise, print the nearest element.

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();
int[] arr = new int[n];

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


arr[i] = [Link]();
}

int key = [Link]();

// Condition 1 : Element Present


for (int i = 0; i < n; i++) {
if (arr[i] == key) {
[Link](arr[i]);
return;
}
}

// Condition 2 : Outside Range


if (key < arr[0]) {
[Link](arr[0]);
return;
}

if (key > arr[n - 1]) {


[Link](arr[n - 1]);
return;
}

// Condition 3 : Key lies between two elements


int closest = 0;

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

if (key > arr[i] && key < arr[i + 1]) {

int diff1 = [Link](arr[i] - key);


int diff2 = [Link](arr[i + 1] - key);

if (diff1 <= diff2) {


closest = arr[i];
} else {
closest = arr[i + 1];
}

break;
}
}

[Link](closest);
}
}
------------------------------------------------------------
EXPLANATION
------------------------------------------------------------
• Perform Binary Search on the sorted array.
• If the key is found, print it immediately.
• If not found, 'low' and 'high' indicate the two closest elements.
• Compare their absolute differences with the key.
• If both are equally close, print the smaller element (arr[high]).

Time Complexity : O(log N)


Space Complexity : O(1)
============================================================
TCS NQT 2027 | July Batch | Round 1
Question 2 – Prime Factors of a Number
============================================================

QUESTION
--------
Given a positive integer N, print all of its prime factors in increasing order.

• If a prime factor occurs multiple times, print it multiple times.

INPUT
-----
• A single integer N.

OUTPUT
------
• Print the prime factors of N separated by spaces.

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

for (int i = 2; i <= [Link](n); i++) {

while (n % i == 0) {
[Link](i + " ");
n /= i;
}
}

if (n > 1) {
[Link](n);
}

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------
• Start checking factors from 2.
• While a number divides N completely, print it and divide N.
• Continue until i × i > N.
• If N is still greater than 1, it is the last prime factor.

Time Complexity : O(√N)


Space Complexity : O(1)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 3 – Kth Best-Selling Product (Min Heap)
============================================================

QUESTION
--------
Amazon is preparing for its annual shopping festival and wants to identify its top-performing
products.

Given the sales count of different products, find the Kth best-selling product.

The Kth best-selling product is the product whose sales rank is exactly K when all products are sorted
in descending order of sales.

The solution must use a Min Heap of size K.

INPUT
-----
• First line contains two integers N and K.
• Second line contains N integers representing the sales count of each product.

OUTPUT
------
• Print the Kth best-selling product's sales count.

CONSTRAINTS
-----------
• 1 ≤ K ≤ N ≤ 10⁵
• Sales count is a positive integer.

SAMPLE INPUT 1
--------------
63
50 20 70 40 90 60

SAMPLE OUTPUT 1
---------------
60
Explanation:
Descending Order → 90 70 60 50 40 20
The 3rd best-selling product is 60.

SAMPLE INPUT 2
--------------
52
15 25 10 40 30

SAMPLE OUTPUT 2
---------------
30

Explanation:
Descending Order → 40 30 25 15 10
The 2nd best-selling product is 30.

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();
int k = [Link]();

int[] arr = new int[n];

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


arr[i] = [Link]();
}

// Sort in Ascending Order


[Link](arr);

// Kth Best-Selling Product (Kth Largest)


[Link](arr[n - k]);
}
}
------------------------------------------------------------
Time Complexity : O(N log N)

Space Complexity : O(1)


============================================================
TCS NQT 2027 | July Batch | Round 1
Question 4 – Time Conversion (12-Hour to 24-Hour Format)
============================================================

QUESTION
--------
Given a time in 12-hour AM/PM format, convert it to 24-hour (military) format.

Note:
• 12:00:00 AM becomes 00:00:00
• 12:00:00 PM remains 12:00:00

INPUT
-----
• A single string representing time in 12-hour format.

Format:
hh:mm:ssAM

or

hh:mm:ssPM

OUTPUT
------
• Return the equivalent time in 24-hour format.

CONSTRAINTS
-----------
• All input times are valid.

SAMPLE INPUT
------------
07:05:45PM

SAMPLE OUTPUT
-------------
19:05:45

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------
import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String time = [Link]();

String period = [Link](8);


int hour = [Link]([Link](0, 2));

if ([Link]("AM")) {

if (hour == 12)
hour = 0;

} else {

if (hour != 12)
hour += 12;
}
[Link]("%02d%s%n", hour, [Link](2, 8));
[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Extract the hour and AM/PM part.


• If AM and hour is 12, change it to 00.
• If PM and hour is not 12, add 12.
• Print the updated hour with minutes and seconds.

Time Complexity : O(1)

Space Complexity : O(1)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 5 – Find the More Expensive Item
============================================================

QUESTION
--------
There are two items A and B with their respective prices.
Determine which item is more expensive.

Conditions:
• If either price is less than 0, print "Invalid input".
• If both prices are equal, print "Prices equal".
• Otherwise, print the higher price followed by "is more expensive".

INPUT
-----
• Two integers A and B representing the prices of the two items.

OUTPUT
------
• Print the required result based on the given conditions.

SAMPLE INPUT 1
--------------
10 15

SAMPLE OUTPUT 1
---------------
15 is more expensive

SAMPLE INPUT 2
--------------
10 10

SAMPLE OUTPUT 2
---------------
Prices equal

SAMPLE INPUT 3
--------------
-5 20

SAMPLE OUTPUT 3
---------------
Invalid input

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


int a = [Link]();
int b = [Link]();

if (a < 0 || b < 0) {
[Link]("Invalid input");
}
else if (a == b) {
[Link]("Prices equal");
}
else {
[Link]([Link](a, b) + " is more expensive");
}

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Read the prices of both items.


• If either price is negative, print "Invalid input".
• If both prices are equal, print "Prices equal".
• Otherwise, print the higher price followed by "is more expensive".

Time Complexity : O(1)


Space Complexity : O(1)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 6 – Postfix Expression Evaluation (Using Stack)
============================================================

QUESTION
--------
Create a Stack class with the following methods:

• push(value)
• pop()
• evaluate()

The stack should be encapsulated (private data) and used to evaluate a valid Postfix Expression.

Supported Operators:
•+
•-
•*
•/

INPUT
-----
• First line contains an integer N (number of tokens).
• Second line contains N space-separated tokens (operands/operators).

OUTPUT
------
• Print the evaluated result of the postfix expression.

SAMPLE INPUT
------------
5
13 5 + 4 -

SAMPLE OUTPUT
-------------
14

Explanation:
13 + 5 = 18
18 - 4 = 14

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

String[] tokens = new String[n];

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


tokens[i] = [Link]();
}

Stack<Integer> stack = new Stack<>();

for (String token : tokens) {

if ([Link]("+") || [Link]("-") ||
[Link]("*") || [Link]("/")) {

int b = [Link]();
int a = [Link]();
switch (token) {
case "+":
[Link](a + b);
break;

case "-":
[Link](a - b);
break;

case "*":
[Link](a * b);
break;

case "/":
[Link](a / b);
break;
}

} else {
[Link]([Link](token));
}
}

[Link]([Link]());

[Link]();
}
}EXPLANATION
------------------------------------------------------------

• Push operands into the stack.


• When an operator is found, pop the top two operands.
• Perform the operation and push the result back.
• After processing all tokens, the remaining stack element is the final answer.

Time Complexity : O(N)


Space Complexity : O(N)

============================================================

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 7 – Largest Rectangle in Histogram
============================================================

QUESTION
--------
Given an array heights[] where each element represents the height of a histogram bar and the width
of every bar is 1, find the largest rectangular area that can be formed inside the histogram.
INPUT
-----
• First line contains an integer N.
• Second line contains N integers representing the heights of the histogram bars.

OUTPUT
------
• Print the largest rectangular area.

SAMPLE INPUT
------------
6
215623

SAMPLE OUTPUT
-------------
10

Explanation:
The largest rectangle is formed using bars with heights 5 and 6.
Area = 5 × 2 = 10.

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();
int[] heights = new int[n];

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


heights[i] = [Link]();
}

int maxArea = 0;

// Consider every bar as the smallest bar


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

int minHeight = heights[i];

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

if (heights[j] < minHeight) {


minHeight = heights[j];
}

int width = j - i + 1;
int area = minHeight * width;

if (area > maxArea) {


maxArea = area;
}
}
}

[Link](maxArea);
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Traverse every possible starting bar.


• Extend the rectangle to the right one bar at a time.
• Keep track of the minimum height in the current range.
• Calculate:
o Width = j - i + 1
o Area = Minimum Height × Width
• Update the maximum area.
• Print the largest rectangle area.

Time Complexity : O(N^2)


Space Complexity : O(1)

============================================================
TCS NQT 2027 | Java Program
Frequency of Characters in a String (Using Array)
============================================================

QUESTION
--------
Given a string, count the frequency of each character using an array.

INPUT
-----
A single string.

OUTPUT
------
Print each character along with its frequency.

SAMPLE INPUT
------------
programming

SAMPLE OUTPUT
-------------
p:1
r:2
o:1
g:2
a:1
m:2
i:1
n:1

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String str = [Link]().toLowerCase();

int[] freq = new int[26];

for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

if (ch >= 'a' && ch <= 'z') {


freq[ch - 'a']++;
}
}

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

if (freq[i] > 0) {
[Link]((char)(i + 'a') + " : " + freq[i]);
}
}

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Create an integer array of size 26.


• Convert each character to an index using (ch - 'a').
• Increment the corresponding array element.
• Traverse the array and print characters with frequency > 0.

Time Complexity : O(N)

Space Complexity : O(1)

============================================================

============================================================
TCS NQT 2027 | July Batch | Round 1 Question 9 – Arithmetic Progression (Nth Term & Sum of N
Terms)
============================================================

QUESTION
An Arithmetic Progression (AP) is a sequence in which the difference between consecutive terms is
constant.
Given the first term (A), the common difference (D), and the number of terms (N):
• Find the Nth term of the Arithmetic Progression. • Find the sum of the first N terms.
INPUT
• First line contains the first term A. • Second line contains the common difference D. • Third line
contains the number of terms N.
OUTPUT
• Print the Nth term. • Print the sum of the first N terms.
SAMPLE INPUT
235
SAMPLE OUTPUT
Nth Term : 14 Sum : 40
Explanation: AP = 2, 5, 8, 11, 14
Nth Term = 14
Sum = 2 + 5 + 8 + 11 + 14 = 40

JAVA SOLUTION
import [Link].*;
public class Main {
public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int a = [Link]();
int d = [Link]();
int n = [Link]();
int nthTerm = a + (n - 1) * d;

int sum = (n * (2 * a + (n - 1) * d)) / 2;

[Link]("Nth Term : " + nthTerm);


[Link]("Sum : " + sum);

[Link]();
}

EXPLANATION
Nth Term Formula: Nth Term = A + (N - 1) × D
Sum Formula: Sum = N × [2A + (N - 1) × D] / 2
• Read A, D and N. • Calculate the Nth term using the AP formula. • Calculate the sum of the first N
terms using the sum formula. • Print both results.
Time Complexity : O(1)
Space Complexity : O(1)
============================================================

============================================================
TCS NQT 2027 | Java Program | Question 10
Fibonacci Series & Sum of First N Terms
============================================================

QUESTION
--------
Given an integer N, generate the first N terms of the Fibonacci series and print their sum.

The Fibonacci series starts with:


0, 1, 1, 2, 3, 5, 8, ...

Each term is the sum of the previous two terms.


INPUT
-----
• A single integer N.

OUTPUT
------
• Print the Fibonacci series.
• Print the sum of the first N terms.

SAMPLE INPUT
------------
7

SAMPLE OUTPUT
-------------
Fibonacci Series : 0 1 1 2 3 5 8
Sum : 20

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int a = 0, b = 1;
int sum = 0;

if (n >= 1) {
[Link](a + " ");
sum += a;
}

if (n >= 2) {
[Link](b + " ");
sum += b;
}

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

int c = a + b;

[Link](c + " ");


sum += c;

a = b;
b = c;
}

[Link]();
[Link]("Sum : " + sum);

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------
• Initialize the first two Fibonacci numbers as 0 and 1.
• Print 0 and 1 separately and add them to the sum.
• From the 3rd term onwards, calculate:
c=a+b
• Print c, update the sum, then update:
a=b
b=c
• Repeat until N terms are generated.

Time Complexity : O(N)

Space Complexity : O(1)

============================================================

============================================================
TCS NQT 2027 | Java Program | Question 11
Integer to Roman Numeral Conversion
============================================================
QUESTION
--------
Given an integer, convert it into its equivalent Roman Numeral
Roman Symbols:
I=1
V=5
X = 10
L = 50
C = 100
D = 500
M = 1000
1513-1000=513-500=13-10=3-1=2-1=1
M D X 1 1 1
Num=1513->MDX111
14->X

INPUT
-----
• A single integer N.

OUTPUT
------
• Print the corresponding Roman Numeral.

CONSTRAINTS
-----------
• 1 ≤ N ≤ 3999

SAMPLE INPUT
------------
1994
SAMPLE OUTPUT
-------------
MCMXCIV

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int num = [Link]();


500
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40,
10, 9, 5, 4, 1};
4→ 1V
String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L",
"XL", "X", "IX", "V", "IV", "I"};

StringBuilder result = new StringBuilder();

for (int i = 0; i < [Link]; i++) {

while (num >= values[i]) {

[Link](roman[i]);
num -= values[i];
}
}

[Link](result);

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Store Roman numeral values in descending order.


• Traverse each value from largest to smallest.
• While the number is greater than or equal to the current value:
- Append the corresponding Roman symbol.
- Subtract the value from the number.
• Continue until the number becomes 0.

Time Complexity : O(1)

Space Complexity : O(1)

============================================================

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 12 – Kth Highest Salaried Person
============================================================

QUESTION
--------
Given the names of employees and their corresponding salaries, sort them in ascending order of
salary and print the sorted list.

Also, print the Kth highest salaried person's name.

INPUT
-----
• First line contains an integer N (number of employees).
• Second line contains N employee names.
• Third line contains N employee salaries.
• Fourth line contains an integer K.

OUTPUT
------
• Print the employees in ascending order of salary.
• Print the Kth highest salaried person's name.

SAMPLE INPUT
------------
4

A B C D
0 1 2 3
2000 3000 1500 4000
4000 3000 2000 1500

[Link](list, [Link]());
3

SAMPLE OUTPUT
-------------
Ascending Order

1500 -c
2000 - a
3000 – b
4000- d

k=n-k

[Link](index) wrong

3rd Highest Person : A

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {


public static void main(String[] args) {

String[] name = {"A", "B", "C", "D"};


int[] marks = {85, 92, 78, 90};
int k = 2;

HashMap<Integer, String> map = new HashMap<>();


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

for (int i = 0; i < [Link]; i++) {


[Link](marks[i], name[i]);
[Link](marks[i]);
}

[Link](list, [Link]());

int kthMark = [Link](k - 1);

[Link]([Link](kthMark));
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Store employee names and salaries in separate arrays.


• Sort the salaries in ascending order.
• Swap the corresponding names whenever salaries are swapped.
• Print the sorted list.
• Since the array is sorted in ascending order, the Kth highest person is at index (N - K).
Time Complexity : O(N²)

Space Complexity : O(1)

============================================================
============================================================
TCS NQT 2027 | July Batch | Round 1
Question 13 – First Unique Element in an Array
============================================================

QUESTION
--------
Given an array of integers, return the first unique element using a HashMap.

The array contains exactly one element that appears only once, while every other element appears
exactly twice.

INPUT
-----
• First line contains an integer N (size of the array).
• Second line contains N integers.

OUTPUT
------
• Print the first element that appears only once.

SAMPLE INPUT
------------
7
2354532

SAMPLE OUTPUT
-------------
4

Explanation:
Frequency of elements:

2 → 2 times
3 → 2 times
5 → 2 times
4 → 1 time

Hence, 4 is the first unique element.

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;
public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int[] arr = new int[n];

HashMap<Integer, Integer> map = new HashMap<>();

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

arr[i] = [Link]();

[Link](arr[i], [Link](arr[i], 0) + 1);


}

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

if ([Link](arr[i]) == 1) {

[Link](arr[i]);
break;
}
}

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Store the frequency of every element using a HashMap.


• Traverse the array again from left to right.
• Print the first element whose frequency is 1.
• Stop after printing the first unique element.

Time Complexity : O(N)

Space Complexity : O(N)

============================================================

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 14 – Print All Indices of the Target Element
============================================================

QUESTION
--------
Given a sorted array and a target element, print all the indices at which the target element is
present.

INPUT
-----
• First line contains an integer N (size of the array).
• Second line contains N sorted integers.
• Third line contains the target element.

OUTPUT
------
• Print all the indices where the target element is present.

SAMPLE INPUT
------------
8

12223445

SAMPLE OUTPUT
-------------
123

Explanation:
The target element 2 occurs at indices 1, 2 and 3.

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int[] arr = new int[n];

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


arr[i] = [Link]();
}
int target = [Link]();

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

if (arr[i] == target) {
[Link](i + " ");
}
}

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Read the sorted array and the target element.


• Traverse the array from left to right.
• Whenever the target element is found, print its index.
• Continue until the end of the array.

Time Complexity : O(N)

Space Complexity : O(1)

============================================================

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 16 – Least Even Sum of Two Prime Numbers
============================================================

QUESTION
--------
Given an array of integers, find the least possible sum of any two prime numbers present in the array
such that their sum is even.

If no such pair exists, print "Not Possible".

INPUT
-----
• First line contains an integer N (size of the array).
• Second line contains N integers.

OUTPUT
------
• Print the least even sum of two prime numbers.

SAMPLE INPUT
------------
6

7 5 2 11 8 3

SAMPLE OUTPUT
-------------
8

Explanation:
Prime Numbers = 7, 5, 2, 11, 3

Possible Even Sums:


7 + 5 = 12
7 + 11 = 18
5+3=8
11 + 3 = 14

Least Even Sum = 8

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

static boolean isPrime(int n) {

if (n < 2)
return false;

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

if (n % i == 0)
return false;
}

return true;
}

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int[] arr = new int[n];

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


arr[i] = [Link]();
}

int sol = 0;

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

if (!isPrime(arr[i]))
continue;

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

if (!isPrime(arr[j]))
continue;

int sum = arr[i] + arr[j];

if (sum % 2 == 0 && sum < minSum) {


minSum = sum;
}
}
}

if (minSum == Integer.MAX_VALUE)
[Link]("Not Possible");
else
[Link](minSum);

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Traverse the array and consider only prime numbers.


• Generate all possible pairs of prime numbers.
• Check whether their sum is even.
• Keep track of the minimum even sum.
• Print the least even sum. If no valid pair exists, print "Not Possible".

Time Complexity : O(N² × √M)


Space Complexity : O(1)
============================================================

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 17 – Highest Scoring Student & Average Marks
============================================================
QUESTION
--------
Given two arrays:

• A string array containing the names of students.


• An integer array containing their corresponding marks.

Print the name of the student who scored the highest marks and the average marks of all students.

Output Format:
[Highest Scoring Student : Average Marks]

INPUT
-----
• First line contains an integer N (number of students).
• Second line contains N student names.
• Third line contains N student marks.

OUTPUT
------
• Print the highest scoring student's name and the average marks in the format:

[StudentName : AverageMarks]

SAMPLE INPUT
------------
3

Ravi ram krish

100 200 300

SAMPLE OUTPUT
-------------
[krish : 200]

Explanation:
Highest Marks = 300 (krish)

Average Marks = (100 + 200 + 300) / 3 = 200

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

int n = [Link]();

String[] name = new String[n];


int[] marks = new int[n];

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


name[i] = [Link]();
}

int sum = 0;
int max = Integer.MIN_VALUE;
int index = 0;

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

int key = [Link]();

sum += marks[i];

if (marks[i] > max) {


max = marks[i];
index = i;
}
}

int average = sum / n;

[Link]("[" + name[index] + " : " + average + "]");

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Read the student names and marks.


• Find the student with the highest marks.
• Calculate the sum of all marks.
• Compute the average marks.
• Print the highest scoring student's name and the average in the required format.

Time Complexity : O(N)

Space Complexity : O(N)

============================================================
============================================================
TCS NQT 2027 | July Batch | Round 1
Question 18 – First Non-Repeating Character
============================================================

QUESTION
--------
Given a string, find the first character that does not repeat.

If no such character exists, print -1.

INPUT
-----
• A single string.

OUTPUT
------
• Print the first non-repeating character.
• If no such character exists, print -1.

SAMPLE INPUT 1
--------------
aabbcdde

SAMPLE OUTPUT 1
---------------
c

SAMPLE INPUT 2
--------------
aabbcc

SAMPLE OUTPUT 2
---------------
-1

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String str = [Link]();

HashMap<Character, Integer> map = new HashMap<>();


// Count frequency
for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

[Link](ch, [Link](ch, 0) + 1);


}

// Find first non-repeating character


for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

if ([Link](ch) == 1) {
[Link](ch);
return;
}
}

[Link](-1);

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Store the frequency of each character using a HashMap.


• Traverse the string from left to right.
• Print the first character whose frequency is 1.
• If no such character exists, print -1.

Time Complexity : O(N)

Space Complexity : O(N)

============================================================

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 19 – Equilibrium Index of an Array
============================================================

QUESTION
--------
Given an array, find an index such that the sum of elements on its left is equal to the sum of
elements on its right.
If no such index exists, print -1.

INPUT
-----
• First line contains an integer N (size of the array).
• Second line contains N integers.

OUTPUT
------
• Print the equilibrium index.
• If no such index exists, print -1.

SAMPLE INPUT 1
--------------
5

13522
Total sum=13

SAMPLE OUTPUT 1
---------------
2

Explanation:
Left Sum = 1 + 3 = 4
Right Sum = 2 + 2 = 4

Hence, index 2 is the equilibrium index.

SAMPLE INPUT 2
--------------
4

1234

SAMPLE OUTPUT 2
---------------
-1

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


int n = [Link]();

int[] arr = new int[n];

int totalSum = 0;

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


arr[i] = [Link]();
totalSum += arr[i];
}

int leftSum = 0;

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

totalSum -= arr[i];

if (leftSum == totalSum) {
[Link](i);
return;
}

leftSum += arr[i];
}

[Link](-1);

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Calculate the total sum of the array.


• Traverse the array from left to right.
• Before checking, subtract the current element from the total sum.
Now, totalSum represents the right-side sum.
• Compare leftSum with totalSum.
• If they are equal, print the current index.
• Otherwise, add the current element to leftSum and continue.
• If no equilibrium index is found, print -1.

Time Complexity : O(N)

Space Complexity : O(1)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 20 – Two Sum (Brute Force)
============================================================

QUESTION
--------
Given a sorted array and a target sum, find two numbers such that they add up to the target.

Print their indices.

If no such pair exists, print -1.

INPUT
-----
• First line contains an integer N (size of the array).
• Second line contains N sorted integers.
• Third line contains the target sum.

OUTPUT
------
• Print the indices of the two numbers whose sum equals the target.
• If no such pair exists, print -1.

SAMPLE INPUT 1
--------------
5

2 7 11 15 18

SAMPLE OUTPUT 1
---------------
01

Explanation:
arr[0] + arr[1] = 2 + 7 = 9

SAMPLE INPUT 2
--------------
5

12345

20

SAMPLE OUTPUT 2
---------------
-1

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------
import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int[] arr = new int[n];

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


arr[i] = [Link]();
}

int target = [Link]();

boolean found = false;

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

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

if (arr[i] + arr[j] == target) {

[Link](i + " " + j);


found = true;
break;
}
}

if (found)
break;
}

if (!found)
[Link](-1);

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Traverse the array using two nested loops.


• Check every possible pair of elements.
• If their sum equals the target, print their indices.
• If no pair is found after checking all pairs, print -1.

Time Complexity : O(N²)

Space Complexity : O(1)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 21 – Transpose of a Matrix
============================================================

QUESTION
--------
Given an N × M matrix, compute its transpose.

In the transpose of a matrix:


• Rows become columns.
• Columns become rows.

INPUT
-----
• First line contains two integers N and M.
• Next N lines contain M integers each.

OUTPUT
------
• Print the transpose of the matrix.

SAMPLE INPUT
------------
23

123
456

SAMPLE OUTPUT
-------------
14
25
36

Explanation:
Original Matrix:

123
456

Transpose:

14
25
36

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();
int m = [Link]();

int[][] arr = new int[n][m];

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

for (int j = 0; j < m; j++) {

arr[i][j] = [Link]();
}
}

for (int j = 0; j < m; j++) {

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

[Link](arr[i][j] + " ");


}

[Link]();
}

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Read the N × M matrix.


• Traverse the matrix column by column.
• For each column, print all the rows.
• This converts rows into columns, producing the transpose.
Time Complexity : O(N × M)

Space Complexity : O(N × M)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 23 – Majority Element
============================================================

QUESTION
--------
Given an array of size N, find the element that appears more than N/2 times.

If no such element exists, print -1.

INPUT
-----
• First line contains an integer N (size of the array).
• Second line contains N integers.

OUTPUT
------
• Print the majority element.
• If no majority element exists, print -1.

SAMPLE INPUT 1
--------------
7

2212322

SAMPLE OUTPUT 1
---------------
2

Explanation:
2 appears 5 times.

N/2 = 3

Since 5 > 3, 2 is the majority element.

SAMPLE INPUT 2
--------------
5

12345

SAMPLE OUTPUT 2
---------------
-1

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int[] arr = new int[n];

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


arr[i] = [Link]();
}

boolean found = false;

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

int count = 0;

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

if (arr[i] == arr[j]) {
count++;
}
}

if (count > n / 2) {
[Link](arr[i]);
found = true;
break;
}
}

if (!found) {
[Link](-1);
}

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Traverse each element in the array.


• Count how many times it appears using another loop.
• If its frequency is greater than N/2, print the element.
• If no such element exists, print -1.

Time Complexity : O(N²)

Space Complexity : O(1)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 24 – Replace Elements with Their Rank
============================================================
QUESTION
Given an array of integers, replace each element with its position (rank) in the sorted list of unique
elements.
• The smallest unique element has rank 1.
• The next smallest unique element has rank 2, and so on.
• If an element appears more than once, assign the same rank to each occurrence.
INPUT
• First line contains an integer N (size of the array).
• Second line contains N integers.
OUTPUT
• Print the rank of each element.
SAMPLE INPUT
5
23 6 4 6 1
SAMPLE OUTPUT
43231

Explanation:

Original Array : 23 6 4 6 1

Unique Sorted Array : 1 4 6 23

Ranks:

1 →1

4 →2

6 →3

23 → 4
Hence,

23 6 4 6 1

43231

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int[] arr = new int[n];


int[] temp = new int[n];

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

arr[i] = [Link]();
temp[i] = arr[i];
}

// Sort the copied array


[Link](temp);

HashMap<Integer, Integer> map = new HashMap<>();

int rank = 1;

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

if (![Link](temp[i])) {

[Link](temp[i], rank);
rank++;
}
}

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

[Link]([Link](arr[i]) + " ");


}
[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Copy the original array into another array.


• Sort the copied array.
• Assign ranks only to unique elements using a HashMap.
• Traverse the original array and print the corresponding rank of each element.

Time Complexity : O(N log N)

Space Complexity : O(N)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 25 – Find the Duplicate and Missing Number
============================================================

QUESTION
--------
An array of size N contains numbers from 0 to N-1.

Exactly one number is repeated and exactly one number is missing.

Find and print:

1. The duplicate number.


2. The missing number.

INPUT
-----
• First line contains an integer N.
• Second line contains N space-separated integers.

OUTPUT
------
• Print the duplicate number.
• Print the missing number.

SAMPLE INPUT
------------
5
012345
012244
Index=-1;
For(int i=0;i<n-1;i++)
{
If(arr[i]==arr[i+1]
Index=arr[i]
Print (duplicate=arr[i]
missing =arr[i]+1
}
Index=2
Index+1→ missing number

Yepo duplicate occur → next element tan missing element


SAMPLE OUTPUT
-------------
Duplicate Number : 2
Missing Number : 3

Explanation:
Numbers should be:
01234

But the array contains:


01224

Hence,
Duplicate = 2
Missing = 3

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int[] arr = new int[n];


int[] freq = new int[n];

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

arr[i] = [Link]();
freq[arr[i]]++;
}
int duplicate = -1;
int missing = -1;

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

if (freq[i] == 2) {
duplicate = i;
}

if (freq[i] == 0) {
missing = i;
}
}

[Link]("Duplicate Number : " + duplicate);


[Link]("Missing Number : " + missing);

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Create a frequency array of size N.


• Count the occurrence of each number.
• The number with frequency 2 is the duplicate.
• The number with frequency 0 is the missing number.
• Print both values.

Time Complexity : O(N)

Space Complexity : O(N)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 26 – +2, -1 String Encoding
============================================================

QUESTION
--------
Given a string, perform +2, -1 encoding based on the character index.

Rules:

• Characters at even index (0, 2, 4, ...) → Move forward by 2 positions.


• Characters at odd index (1, 3, 5, ...) → Move backward by 1 position.

Special Cases:
•Z→B
•z→b
•A→Z
•a→z
•9→1
•0→9

INPUT
-----
• A single string.
Char ch=’a’
Ch+=1
Print(ch)
→b

Char ch=’a’
Ch++;
Print(ch)
→b

Char ch=’a’
Ch=ch+1;
Print(ch)
→ERROR

OUTPUT
------
• Print the encoded string.

SAMPLE INPUT
------------
AbcZ0

For(int i=0;i<[Link]();i++)
{
If(i%2==0)
{
(char)[Link](i)+2

a - 97
Z - 90
A - 65
z - 122

SAMPLE OUTPUT
-------------
CaeY2
Explanation:

Index Character Operation Result

0 A +2 C
1 b -1 a
2 c +2 e
3 Z -1 Y
4 0 +2 2

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String str = [Link]();

String result = "";

for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

if (i % 2 == 0) {

// Even Index : +2

if (ch == 'Z')
ch = 'B';
else if (ch == 'z')
ch = 'b';
else if (ch == '9')
ch = '1';
else
ch += 2;

} else {

// Odd Index : -1

if (ch == 'A')
ch = 'Z';
else if (ch == 'a')
ch = 'z';
else if (ch == '0')
ch = '9';
else
ch -= 1;
}

result += ch;
}

[Link](result);

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Traverse the string character by character.


• If the index is even, move the character forward by 2.
• If the index is odd, move the character backward by 1.
• Handle wrap-around cases for alphabets and digits.
• Print the encoded string.

Time Complexity : O(N)

Space Complexity : O(N)

============================================================
TCS NQT 2027 | July Batch | Round 1
Question 27 – Remove Duplicates and Reverse the Array
============================================================

QUESTION
--------
Given a sequence of integers:

1. Remove duplicate elements while keeping only the first occurrence.


2. Reverse the remaining elements.
3. Print the reversed sequence.

INPUT
-----
• First line contains an integer N.
• Second line contains N integers.

OUTPUT
------
• Print the reversed array after removing duplicates.
SAMPLE INPUT
------------
6

141324

SAMPLE OUTPUT
-------------
1432
2341

Explanation:

Original Array:
141324

After Removing Duplicates:


1432

After Reversing:
2341

------------------------------------------------------------
JAVA SOLUTION
------------------------------------------------------------

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int[] arr = new int[n];


int[] unique = new int[n];

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


arr[i] = [Link]();
}

int size = 0;

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

boolean found = false;


for (int j = 0; j < size; j++) {

if (arr[i] == unique[j]) {
found = true;
break;
}
}

if (!found) {
unique[size] = arr[i];
size++;
}
}

// Print in Reverse Order


for (int i = size - 1; i >= 0; i--) {
[Link](unique[i] + " ");
}

[Link]();
}
}

------------------------------------------------------------
EXPLANATION
------------------------------------------------------------

• Read all elements into an array.


• Create another array to store unique elements.
• For each element, check if it already exists in the unique array.
• If not, add it to the unique array.
• Finally, traverse the unique array in reverse order and print the elements.

Time Complexity : O(N²)

Space Complexity : O(N)

You might also like