Actual questions from the June 2025 TCS National Qualifier Test with complete solutions in Java, C++, and Python.
📅 5th June 2026 – Q1 & Q2📅 9th June 2026 – Q3 & Q4
These are verified, student-reported questions from the TCS NQT 2027 (Batch) assessment held in June 2025.
Questions 1 & 2 were reported from the 5th June 2026 slot; Questions 3 & 4 from the 9th June 2026 slot.
Use this guide to understand the pattern, practice the problems, and go in prepared.
You are given an array of integers representing coin values and an integer target. Find two different indices such that the sum of coin values at those indices equals the target. Return the indices of the two coins.
Use a HashMap to store each value and its index as you iterate.
For each element, compute complement = target - coins[i].
If complement exists in the map, return both indices immediately.
Single-pass O(n) — much faster than a brute-force nested loop.
⏱ Time: O(n)🗂 Space: O(n)
Solution
import java.util.HashMap;
public classSolution {
public static int[] coinPairIndices(int[] coins, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < coins.length; i++) {
int complement = target - coins[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(coins[i], i);
}
return new int[] { -1, -1 }; // no pair found
}
public static voidmain(String[] args) {
int[] coins = {2, 7, 11, 15};
int[] result = coinPairIndices(coins, 9);
System.out.println("[" + result[0] + ", " + result[1] + "]"); // [0, 1]
}
}
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> coinPairIndices(vector<int>& coins, int target) {
unordered_map<int, int> mp;
for (int i = 0; i < coins.size(); i++) {
int complement = target - coins[i];
if (mp.count(complement))
return { mp[complement], i };
mp[coins[i]] = i;
}
return { -1, -1 };
}
intmain() {
vector<int> coins = {2, 7, 11, 15};
auto res = coinPairIndices(coins, 9);
cout << "[" << res[0] << ", " << res[1] << "]" << endl; // [0, 1]
}
defcoin_pair_indices(coins, target):
seen = {}
for i, val in enumerate(coins):
complement = target - val
if complement in seen:
return [seen[complement], i]
seen[val] = i
return [-1, -1]
# Test
coins = [2, 7, 11, 15]
print(coin_pair_indices(coins, 9)) # [0, 1]
2
Merge Two Arrays into a Sorted Array
Easy
Problem Statement
You are given two arrays: Array A sorted in ascending order and Array B sorted in descending order. Create a new array containing all elements from both arrays sorted in ascending order.
Reverse array B (now it's ascending), or use a reverse pointer.
Merge both sorted arrays using the classic two-pointer technique.
Compare elements from A and reversed-B, push the smaller one.
Flush remaining elements of either array at the end.
⏱ Time: O(n + m)🗂 Space: O(n + m)
Solution
import java.util.Arrays;
public classMergeArrays {
public static int[] mergeSorted(int[] A, int[] B) {
// Reverse B to make it ascendingint left = 0, right = B.length - 1;
while (left < right) {
int tmp = B[left]; B[left] = B[right]; B[right] = tmp;
left++; right--;
}
// Two-pointer mergeint[] result = new int[A.length + B.length];
int i = 0, j = 0, k = 0;
while (i < A.length && j < B.length)
result[k++] = A[i] <= B[j] ? A[i++] : B[j++];
while (i < A.length) result[k++] = A[i++];
while (j < B.length) result[k++] = B[j++];
return result;
}
public static voidmain(String[] args) {
int[] A = {1,3,5,7}, B = {10,8,6,4};
System.out.println(Arrays.toString(mergeSorted(A, B)));
// [1, 3, 4, 5, 6, 7, 8, 10]
}
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> mergeSorted(vector<int> A, vector<int> B) {
reverse(B.begin(), B.end());
vector<int> result;
int i = 0, j = 0;
while (i < A.size() && j < B.size())
result.push_back(A[i] <= B[j] ? A[i++] : B[j++]);
while (i < A.size()) result.push_back(A[i++]);
while (j < B.size()) result.push_back(B[j++]);
return result;
}
intmain() {
vector<int> A = {1,3,5,7}, B = {10,8,6,4};
for (auto v : mergeSorted(A, B)) cout << v << " ";
// 1 3 4 5 6 7 8 10
}
defmerge_sorted(A, B):
B_asc = B[::-1] # reverse B to ascending
result = []
i = j = 0while i < len(A) and j < len(B_asc):
if A[i] <= B_asc[j]:
result.append(A[i]); i += 1else:
result.append(B_asc[j]); j += 1
result.extend(A[i:])
result.extend(B_asc[j:])
return result
print(merge_sorted([1,3,5,7], [10,8,6,4]))
# [1, 3, 4, 5, 6, 7, 8, 10]
📅 9th June 2026
3
First Occurrence of Target in an Array
Easy
Problem Statement
Given an array of integers and a target value, find the index of the first occurrence of the target in the array. If the target is not present, return -1.
Examples
Example 1 — Target found:arr = [4, 2, 7, 2, 9, 2], target = 2 → Output: 1Target 2 appears at indices 1, 3, 5. First occurrence is index 1.
Example 2 — Target not found:arr = [5, 8, 1, 6], target = 3 → Output: -1
Approach
Simple linear scan — iterate left to right.
Return the index immediately when arr[i] == target.
If the loop ends without a match, return -1.
⏱ Time: O(n)🗂 Space: O(1)
Solution
public classFirstOccurrence {
public static int firstOccurrence(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) return i;
}
return -1;
}
public static voidmain(String[] args) {
int[] arr = {4, 2, 7, 2, 9, 2};
System.out.println(firstOccurrence(arr, 2)); // 1
System.out.println(firstOccurrence(arr, 3)); // -1
}
}
#include <iostream>
#include <vector>
using namespace std;
intfirstOccurrence(vector<int>& arr, int target) {
for (int i = 0; i < arr.size(); i++)
if (arr[i] == target) return i;
return -1;
}
intmain() {
vector<int> arr = {4,2,7,2,9,2};
cout << firstOccurrence(arr, 2) << endl; // 1
cout << firstOccurrence(arr, 3) << endl; // -1
}
deffirst_occurrence(arr, target):
for i, val in enumerate(arr):
if val == target:
return i
return -1print(first_occurrence([4,2,7,2,9,2], 2)) # 1print(first_occurrence([5,8,1,6], 3)) # -1
4
Minimum Depth of a Binary Tree
Medium
Problem Statement
Given the root of a binary tree, return its minimum depth — the number of nodes along the shortest path from the root node down to the nearest leaf node. A leaf node has no left or right children.
Example
Input Tree: 1
/ \
2 3
/
4Output:2Shortest path: 1 → 3 (length 2). Node 3 is a leaf.
Approach
Use Breadth-First Search (BFS) — guaranteed to reach the nearest leaf first.
Process level by level; the moment you encounter a leaf, return the current depth.
BFS is preferred over DFS here since DFS explores full branches before finding the minimum.
import java.util.LinkedList;
import java.util.Queue;
public classMinDepth {
static classTreeNode {
int val;
TreeNode left, right;
TreeNode(int v) { val = v; }
}
public static int minDepth(TreeNode root) {
if (root == null) return0;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int depth = 1;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
if (node.left == null && node.right == null)
return depth; // leaf reached!if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
depth++;
}
return depth;
}
public static voidmain(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
System.out.println(minDepth(root)); // 2
}
}
#include <iostream>
#include <queue>
using namespace std;
structTreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};
intminDepth(TreeNode* root) {
if (!root) return0;
queue<TreeNode*> q;
q.push(root);
int depth = 1;
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
auto node = q.front(); q.pop();
if (!node->left && !node->right) return depth;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
depth++;
}
return depth;
}
intmain() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
cout << minDepth(root) << endl; // 2
}
from collections import deque
classTreeNode:
def__init__(self, val=0):
self.val = val
self.left = self.right = Nonedefmin_depth(root):
if not root: return0
q = deque([(root, 1)])
while q:
node, depth = q.popleft()
if not node.left and not node.right:
return depth # leaf!if node.left: q.append((node.left, depth + 1))
if node.right: q.append((node.right, depth + 1))
# Build: 1 → (2→4, 3)
root = TreeNode(1)
root.left, root.right = TreeNode(2), TreeNode(3)
root.left.left = TreeNode(4)
print(min_depth(root)) # 2
💡 TCS NQT Exam Tips & Pattern Analysis
Array problems dominate: 3 of 4 questions involved arrays. Master sliding window, two pointers, and HashMap lookups.
Tree problems are picking up: Binary tree BFS/DFS is now a regular topic. Practice LeetCode Easy–Medium tree problems.
Complexity matters: TCS test cases often include large inputs. Always aim for O(n) or O(n log n) — avoid O(n²) brute force.
Edge cases are tested: Target not found, empty arrays, single-node trees — always code defensively.
Time limit is tight: Aim to solve Easy questions in under 15 minutes, Medium in 20–25 minutes.
Choose your language wisely: Java and Python are safest; C++ is faster but requires careful memory management.
Practice on CodeChef / LeetCode: Filter by "TCS NQT" tags or Easy–Medium array and tree questions.
TCS NQT Python Coding Questions 2026
🔥 Verified Exam Questions • 2026
60 Actual TCS NQT Python Coding Questions Really Asked in the Assessment Round
Not guess work. Not practice sheets. These are the exact story-based and algorithm problems that appeared in TCS NQT assessment rounds across 2024–2026 batches — with full Python solutions, approach, and complexity analysis.
CampusMonk60 Verified QuestionsPython SolutionsUpdated May 2026
60
Questions
8
Categories
1–2
Qs in Exam
90 min
Time Limit
Python
Solutions
500,000+ students sit for TCS NQT every year. Most of them practise random questions. The ones who crack it practise the right questions. This blog gives you exactly that — the 60 Python coding problems TCS actually asked.
Here is something most preparation blogs will not tell you: TCS NQT coding questions are story-based. They wrap a simple algorithm inside a narrative — a chocolate factory, a stock market trader, a scientist counting Sundays. Strip the story, see the algorithm, write the code.
This guide does exactly that for all 60 questions.
⚠ TCS NQT Coding Round — What You Need to Know
Foundation Section: 1 coding question, medium difficulty, 30–45 minutes
TITA questions: Type In The Answer — no options, must match exactly
Pattern: Story wraps the algorithm. Decode the story first.
⚡ Pro Tip: For every question, use the "strip the story" method. Ask: What is the input? What transformation? What is the output? The actual algorithm is usually O(n) or O(n log n).
Section 1 — Most Asked
📚 Story-Based Problems — Q1 to Q15
Story-Based Coding Problems
These are the most important questions to practise. TCS wraps every algorithm inside a story. Once you learn to strip the story and identify the algorithm, these become very straightforward.
The TCS Story Formula: Character + Problem + Array/String + Expected Output. Strip the narrative, find the data structure, write the function.
1
EasyArrays / Story
Chocolate Factory — Push Zeros to End
A chocolate factory packs chocolates into packets. Each packet is represented by an integer where 0 means empty. Move all empty packets (zeros) to the end of the array while maintaining the relative order of filled packets.
Input 1
[4,5,0,1,9,0,5,0]
Output 1
4 5 1 9 5 0 0 0
Input 2
[6,0,1,8,0,2]
Output 2
6 1 8 2 0 0
⚙ Approach Two-pointer: maintain a write pointer for non-zero values. Place each non-zero at the pointer, then backfill remaining positions with zeros.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
pos = 0
for x in arr:
if x != 0:
arr[pos] = x
pos += 1
while pos < n:
arr[pos] = 0
pos += 1
print(*arr)
Time: O(n)Space: O(1)
2
EasyDate Logic
Jack's Sunday Count
Jack loves Sundays! Given the starting weekday and the total number of days N in the month, count how many Sundays fall within those N days.
Input 1
mon, 13
Output 1
2
Input 2
sun, 30
Output 2
5
⚙ Approach Map days to 0-6 (Mon=0...Sun=6). Days to first Sunday = (6-start)%7. If >= n, answer is 0. Else: 1 + (n - to_sun - 1) // 7.
Python Solution ✔ Verified
day = input().strip().lower()
n = int(input())
days = {"mon":0,"tue":1,"wed":2,"thu":3,"fri":4,"sat":5,"sun":6}
d = days[day]
to_sun = (6 - d) % 7
if to_sun >= n:
print(0)
else:
print(1 + (n - to_sun - 1) // 7)
Time: O(1)Space: O(1)
3
EasyGreedy
Rahul's Stock Profit — Maximum Profit
Rahul is a stock trader. Given prices[] where prices[i] is the price on day i, find the maximum profit from one buy and one future sell. Return 0 if no profit is possible.
Input 1
[7,1,5,3,6,4]
Output 1
5
Input 2
[7,6,4,3,1]
Output 2
0
⚙ Approach Track the minimum price seen so far. At each price compute profit = price - min_so_far. Update the maximum profit. Single pass.
Python Solution ✔ Verified
n = int(input())
prices = [int(input()) for _ in range(n)]
min_price = float('inf')
max_profit = 0
for p in prices:
min_price = min(min_price, p)
max_profit = max(max_profit, p - min_price)
print(max_profit)
Time: O(n)Space: O(1)
4
EasyCombinatorics
COVID Handshake Problem
During a conference, every person shakes hands with every other person exactly once. Given T test cases each with N people, find the total handshakes for each case.
Input 1
2
1
4
Output 1
0
6
Input 2
1
10
Output 2
45
⚙ Approach Each handshake involves 2 unique people. Formula: N*(N-1)//2. Pure math — no loops needed.
Python Solution ✔ Verified
t = int(input())
for _ in range(t):
n = int(input())
print(n * (n - 1) // 2)
Time: O(T)Space: O(1)
5
EasyStrings
Curtain Company — Max 'a' in Substrings
A curtain company has a string of 'a' (aqua) and 'b' (black) curtains packed into boxes of size L. Find the maximum number of aqua curtains ('a') in any single box.
Input 1
bbbaaababa, 3
Output 1
3
Input 2
aaabbb, 2
Output 2
2
⚙ Approach Slice the string into chunks of size L. Count 'a' in each chunk and track the maximum.
Python Solution ✔ Verified
s = input().strip()
L = int(input())
best = 0
for i in range(0, len(s), L):
best = max(best, s[i:i+L].count('a'))
print(best)
Time: O(n)Space: O(1)
6
MediumMath
Intelligence Agency — Repeated Digit Sum
An intelligence agency assigns codes by repeatedly summing digits of N for R times. Return the final result. If R=0, return 0.
Input 1
99, 3
Output 1
9
Input 2
999, 1
Output 2
27
⚙ Approach Iteratively compute digit sum R times. Optimisation: if n < 10 at any point, break early — single digit wont change.
Python Solution ✔ Verified
n = int(input())
r = int(input())
if r == 0:
print(0)
else:
for _ in range(r):
n = sum(int(d) for d in str(n))
if n < 10:
break
print(n)
Time: O(R*digits)Space: O(1)
7
EasyXOR
Find the Odd Occurring Element
In a spy agency roster, every agent appears an even number of times except one. Given the array, find the odd-occurring element. No element appears more than twice consecutively.
Input 1
[2,2,3,1,1]
Output 1
3
Input 2
[4,1,4,2,2]
Output 2
1
⚙ Approach XOR of a number with itself is 0. XOR of a number with 0 is itself. XOR all elements — even-frequency elements cancel, leaving the odd one.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
result = 0
for x in arr:
result ^= x
print(result)
Time: O(n)Space: O(1)
8
MediumArrays
Airport Security — Sort 0s, 1s and 2s
At airport security, items are tagged: 0=safe, 1=neutral, 2=dangerous. Sort all items in a single pass without extra array.
Input 1
[0,1,2,0,1,2]
Output 1
0 0 1 1 2 2
Input 2
[2,0,1]
Output 2
0 1 2
⚙ Approach Dutch National Flag: three pointers low, mid, high. If arr[mid]==0 swap with low; if ==2 swap with high; else advance mid.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
low = mid = 0
high = n - 1
while mid <= high:
if arr[mid] == 0:
arr[low], arr[mid] = arr[mid], arr[low]
low += 1; mid += 1
elif arr[mid] == 2:
arr[mid], arr[high] = arr[high], arr[mid]
high -= 1
else:
mid += 1
print(*arr)
Time: O(n)Space: O(1)
9
MediumMath
Round Table Conference — Circular Arrangements
N world leaders sit around a circular table. The President and PM of India must always sit next to each other. Find the number of valid arrangements.
Input 1
4
Output 1
12
Input 2
5
Output 2
48
⚙ Approach Treat President+PM as one unit: (N-1) members in circle = (N-2)! ways. The pair can swap in 2! = 2 ways. Answer = 2 * (N-2)!
Python Solution ✔ Verified
import math
n = int(input())
print(2 * math.factorial(n - 2))
Time: O(n)Space: O(1)
10
EasyBit Manipulation
Toggle Bits of a Number
Given a positive integer N, convert it to binary, toggle all bits, and return the decimal value.
Input 1
5
Output 1
2
Input 2
10
Output 2
5
⚙ Approach Create a mask of all 1s with the same bit length as N: mask = (1 << n.bit_length()) - 1. XOR N with mask.
A gemstone type is 'radiant' if it appears in every rock formation (string). Given N rock formations, count the number of radiant gemstone types.
Input 1
3
abc
acd
ac
Output 1
2
Input 2
2
abc
def
Output 2
0
⚙ Approach For each formation take the set of unique characters. Intersect all sets. Count elements in the final intersection.
Python Solution ✔ Verified
n = int(input())
sets = [set(input().strip()) for _ in range(n)]
common = sets[0]
for s in sets[1:]:
common &= s
print(len(common))
Time: O(n*m)Space: O(m)
12
EasyArrays
Count Array Leaders
A leader is an element strictly greater than all elements before it (to its left). The first element is always a leader. Count all leaders.
Input 1
[7,4,8,2,9]
Output 1
3
Input 2
[3,4,5,8,9]
Output 2
5
⚙ Approach Scan left to right tracking the running maximum. If current element > running max, it's a new leader.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
count = 1
mx = arr[0]
for x in arr[1:]:
if x > mx:
count += 1
mx = x
print(count)
Time: O(n)Space: O(1)
13
EasyStrings
File Name Validation
Validate a file name: must start with alphanumeric, contain exactly one dot, no spaces, and extension must be one of: exe, pdf, txt, py, java.
Input 1
file.txt
Output 1
Valid
Input 2
123file.cpp
Output 2
Invalid
Input 3
.hidden
Output 3
Invalid
⚙ Approach Split by dot. Check: starts alphanumeric, no spaces, exactly one dot, valid extension.
Python Solution ✔ Verified
fname = input().strip()
valid_ext = {"exe","pdf","txt","py","java"}
if " " in fname or fname.count(".") != 1:
print("Invalid")
else:
name, ext = fname.split(".")
if name and name[0].isalnum() and ext in valid_ext:
print("Valid")
else:
print("Invalid")
Time: O(n)Space: O(1)
14
EasyCombinatorics
College Timetable — Arrange Subjects
A college has N subjects to schedule per day. Each subject must appear exactly once. How many different daily timetables (arrangements) are possible?
Input 1
3
Output 1
6
Input 2
5
Output 2
120
⚙ Approach This is simply N! (N factorial). Each arrangement is a permutation of N subjects.
Python Solution ✔ Verified
import math
n = int(input())
print(math.factorial(n))
Time: O(n)Space: O(1)
15
MediumArrays
Library Fine Calculation
A library charges fines: Rs.5/day for days 1-5 late, Rs.10/day for days 6-10, Rs.20/day beyond 10 days. Given late days for N books, compute total fine.
Input 1
3
3 7 12
Output 1
75
⚙ Approach For each book's late days apply the tiered formula: 5*min(d,5) + 10*max(0,min(d-5,5)) + 20*max(0,d-10).
Python Solution ✔ Verified
n = int(input())
days_list = list(map(int, input().split()))
total = 0
for d in days_list:
if d <= 0:
continue
elif d <= 5:
total += 5 * d
elif d <= 10:
total += 25 + 10 * (d - 5)
else:
total += 25 + 50 + 20 * (d - 10)
print(total)
Time: O(n)Space: O(1)
Section 2
📈 Array Manipulation — Q16 to Q25
Array Manipulation
Arrays are the most tested data structure in TCS NQT. Know these 10 patterns cold.
16
EasyArrays
Find the Second Largest Element
Given an array of integers, find the second largest unique element. If no second largest exists, print -1.
Input 1
[1,2,3,4,5]
Output 1
4
Input 2
[5,5,5]
Output 2
-1
⚙ Approach Convert to set, sort descending. Second element is the answer if it exists.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
unique = sorted(set(arr), reverse=True)
print(unique[1] if len(unique) >= 2 else -1)
Time: O(n log n)Space: O(n)
17
EasyArrays
Reverse an Array
Given an array of N integers, reverse the array in-place and print the result.
Input 1
[1,2,3,4,5]
Output 1
5 4 3 2 1
Input 2
[10,20]
Output 2
20 10
⚙ Approach Use Python's slice notation arr[::-1] for a clean one-liner reversal.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
print(*arr[::-1])
Time: O(n)Space: O(1)
18
EasyArrays
Remove Duplicates Preserving Order
Given an array of integers, remove all duplicate elements and print unique elements in their original order of first occurrence.
Input 1
[1,2,2,3,4,4,5]
Output 1
1 2 3 4 5
Input 2
[3,1,3,2,1]
Output 2
3 1 2
⚙ Approach Track seen elements with a set while preserving insertion order.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
seen = set()
result = []
for x in arr:
if x not in seen:
seen.add(x)
result.append(x)
print(*result)
Time: O(n)Space: O(n)
19
MediumArrays
Find All Pairs with Given Sum
Given an array of integers and target sum K, find and print all unique pairs (a,b) where a+b==K and a<=b.
Input 1
[1,2,3,4,5], K=6
Output 1
(1,5) (2,4)
Input 2
[1,1,2,3], K=4
Output 2
(1,3)
⚙ Approach Use a hash set. For each element, check if K-element exists in seen set. Print unique pairs only.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
k = int(input())
seen = set()
pairs = set()
for x in arr:
comp = k - x
if comp in seen:
pair = (min(x,comp), max(x,comp))
if pair not in pairs:
print(pair)
pairs.add(pair)
seen.add(x)
Time: O(n)Space: O(n)
20
EasyArrays
Count Frequency of Each Element
Given an array of N integers, print the frequency of each unique element in the order they first appear.
Input 1
[1,2,2,3,1,4]
Output 1
1:2 2:2 3:1 4:1
Input 2
[5,5,5]
Output 2
5:3
⚙ Approach Use an OrderedDict to count while preserving first-appearance order.
Python Solution ✔ Verified
from collections import OrderedDict
n = int(input())
arr = [int(input()) for _ in range(n)]
freq = OrderedDict()
for x in arr:
freq[x] = freq.get(x, 0) + 1
for k, v in freq.items():
print(f"{k}:{v}")
Time: O(n)Space: O(n)
21
MediumArrays
Maximum Subarray Sum (Kadane's Algorithm)
Given an array of integers (may contain negatives), find the maximum sum of any contiguous subarray.
Input 1
[-2,1,-3,4,-1,2,1,-5,4]
Output 1
6
Input 2
[1,2,3,-2,5]
Output 2
9
⚙ Approach Kadane's: track current_sum and max_sum. At each element: current_sum = max(element, current_sum + element).
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
cur = max_s = arr[0]
for x in arr[1:]:
cur = max(x, cur + x)
max_s = max(max_s, cur)
print(max_s)
Time: O(n)Space: O(1)
22
EasyArrays
Rotate Array by K Positions (Right Rotation)
Given an array and integer K, rotate the array to the right by K positions.
n = int(input())
nums = [int(input()) for _ in range(n)]
slow = fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
print(slow)
Time: O(n)Space: O(1)
25
MediumArrays
Find the Longest Consecutive Sequence
Given an unsorted array, find the length of the longest sequence of consecutive integers.
Input 1
[100,4,200,1,3,2]
Output 1
4
Input 2
[0,3,7,2,5,8,4,6,0,1]
Output 2
9
⚙ Approach Convert to set. For each element that is a sequence start (element-1 not in set), count consecutive elements.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
num_set = set(arr)
best = 0
for x in num_set:
if x - 1 not in num_set:
cur, streak = x, 1
while cur + 1 in num_set:
cur += 1
streak += 1
best = max(best, streak)
print(best)
Time: O(n)Space: O(n)
Section 3
🔠 String Operations — Q26 to Q35
String Operations
String problems appear in the Foundation section. Python string methods make most of these elegant one-liners.
26
EasyStrings
Check if String is Palindrome
Given a string, check if it reads the same forwards and backwards (case-insensitive). Print 'Yes' or 'No'.
Input 1
racecar
Output 1
Yes
Input 2
hello
Output 2
No
⚙ Approach Convert to lowercase. Compare string with its reverse using slicing.
Python Solution ✔ Verified
s = input().strip().lower()
print("Yes" if s == s[::-1] else "No")
Time: O(n)Space: O(n)
27
EasyStrings
Check if Two Strings are Anagrams
Given two strings, check if they are anagrams (same characters with same frequencies, case-insensitive).
Input 1
listen, silent
Output 1
Yes
Input 2
hello, world
Output 2
No
⚙ Approach Use Counter from collections to compare character frequencies.
Python Solution ✔ Verified
from collections import Counter
s1 = input().strip().lower()
s2 = input().strip().lower()
print("Yes" if Counter(s1) == Counter(s2) else "No")
Time: O(n)Space: O(n)
28
EasyStrings
Count Vowels and Consonants
Given a string, count the number of vowels and consonants (ignore spaces and special characters).
Input 1
Hello World
Output 1
V:3 C:7
Input 2
aeiou
Output 2
V:5 C:0
⚙ Approach Iterate characters. Count alphabetic ones in vowel set vs not.
Python Solution ✔ Verified
s = input().strip().lower()
v = sum(1 for c in s if c in 'aeiou')
con = sum(1 for c in s if c.isalpha() and c not in 'aeiou')
print(f"V:{v} C:{con}")
Time: O(n)Space: O(1)
29
EasyStrings
Find the First Non-Repeating Character
Given a string, find and print the first character that does not repeat. If all characters repeat, print -1.
Input 1
aabbcde
Output 1
c
Input 2
aabb
Output 2
-1
⚙ Approach Count frequencies using Counter. Scan original string for first character with frequency 1.
Python Solution ✔ Verified
from collections import Counter
s = input().strip()
freq = Counter(s)
for c in s:
if freq[c] == 1:
print(c)
break
else:
print(-1)
Time: O(n)Space: O(n)
30
EasyStrings
Reverse Words in a Sentence
Given a sentence, reverse the order of words (not individual characters). Extra spaces should be removed.
Input 1
Hello World How
Output 1
How World Hello
Input 2
TCS NQT
Output 2
NQT TCS
⚙ Approach Split the string by whitespace (handles multiple spaces), reverse the list, join.
Python Solution ✔ Verified
s = input()
print(' '.join(s.split()[::-1]))
Time: O(n)Space: O(n)
31
MediumStrings
Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring containing no repeating characters.
Input 1
abcabcbb
Output 1
3
Input 2
bbbbb
Output 2
1
Input 3
pwwkew
Output 3
3
⚙ Approach Sliding window with a set: expand right, shrink from left when a duplicate is found.
Python Solution ✔ Verified
s = input().strip()
seen = set()
left = max_len = 0
for right, c in enumerate(s):
while c in seen:
seen.remove(s[left])
left += 1
seen.add(c)
max_len = max(max_len, right - left + 1)
print(max_len)
Time: O(n)Space: O(k)
32
EasyStrings
Count Occurrences of a Pattern (Overlapping)
Given a text string and a pattern, count the number of times the pattern appears (overlapping matches counted).
Input 1
aaaa, aa
Output 1
3
Input 2
abab, ab
Output 2
2
⚙ Approach Loop from 0 to len(text)-len(pat)+1 and check each window.
Python Solution ✔ Verified
text = input().strip()
pat = input().strip()
count = sum(1 for i in range(len(text)-len(pat)+1)
if text[i:i+len(pat)] == pat)
print(count)
Time: O(n*m)Space: O(1)
33
EasyStrings
String Compression — Run-Length Encoding
Compress a string using run-length encoding: replace consecutive repeating characters with character + count. If compressed >= original length, return original.
Input 1
aabcccdddd
Output 1
a2bc3d4
Input 2
abc
Output 2
abc
⚙ Approach Iterate tracking current character and count. Build compressed string. Return shorter of the two.
Python Solution ✔ Verified
s = input().strip()
if not s:
print(s)
else:
res = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
res.append(s[i-1] + (str(count) if count > 1 else ""))
count = 1
res.append(s[-1] + (str(count) if count > 1 else ""))
compressed = "".join(res)
print(compressed if len(compressed) < len(s) else s)
Time: O(n)Space: O(n)
34
MediumStrings
Check if String is Rotation of Another
Given two strings S1 and S2 of the same length, check if S2 is a rotation of S1.
Input 1
abcde, cdeab
Output 1
Yes
Input 2
abcde, abced
Output 2
No
⚙ Approach S2 is a rotation of S1 if and only if S2 is a substring of S1+S1.
Python Solution ✔ Verified
s1 = input().strip()
s2 = input().strip()
print("Yes" if len(s1)==len(s2) and s2 in s1+s1 else "No")
Time: O(n)Space: O(n)
35
MediumStrings
Longest Common Prefix of N Strings
Given N strings, find their longest common prefix. If there is no common prefix, print an empty string.
Input 1
3
flower
flow
flight
Output 1
fl
Input 2
2
dog
racecar
Output 2
⚙ Approach Sort the strings lexicographically. Compare only the first and last string character by character.
Python Solution ✔ Verified
n = int(input())
strs = [input().strip() for _ in range(n)]
strs.sort()
prefix = []
for a, b in zip(strs[0], strs[-1]):
if a == b:
prefix.append(a)
else:
break
print(''.join(prefix) if prefix else "")
Time: O(n log n + m)Space: O(m)
Section 4
🔢 Number Theory & Math — Q36 to Q45
Number Theory & Mathematics
Prime checks, factorials, Fibonacci, GCD/LCM appear in both Foundation and Advanced sections.
36
EasyNumber Theory
Check Prime Number
Given a positive integer N, determine if it is prime. Print 'Prime' or 'Not Prime'.
Input 1
7
Output 1
Prime
Input 2
12
Output 2
Not Prime
Input 3
1
Output 3
Not Prime
⚙ Approach Check divisibility from 2 to sqrt(N). Any divisor found means not prime.
Python Solution ✔ Verified
n = int(input())
def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5)+1):
if n % i == 0: return False
return True
print("Prime" if is_prime(n) else "Not Prime")
Time: O(sqrt(n))Space: O(1)
37
EasyNumber Theory
Find GCD and LCM
Given two integers A and B, print their GCD (Greatest Common Divisor) and LCM (Least Common Multiple).
Input 1
12 18
Output 1
GCD:6 LCM:36
Input 2
5 7
Output 2
GCD:1 LCM:35
⚙ Approach Use Euclidean algorithm for GCD. LCM = (a * b) // GCD.
Python Solution ✔ Verified
from math import gcd
a, b = int(input()), int(input())
g = gcd(a, b)
print(f"GCD:{g} LCM:{(a*b)//g}")
Time: O(log min(a,b))Space: O(1)
38
EasyNumber Theory
Armstrong Number Check
A number is Armstrong if sum of each digit raised to the power of total digits equals the number. Example: 153 = 1^3 + 5^3 + 3^3. Check if N is Armstrong.
Input 1
153
Output 1
Yes
Input 2
370
Output 2
Yes
Input 3
123
Output 3
No
⚙ Approach Count digits k. Compute sum of digit^k. Compare with original number.
Python Solution ✔ Verified
n = int(input())
digits = str(n)
k = len(digits)
print("Yes" if n == sum(int(d)**k for d in digits) else "No")
Time: O(d)Space: O(1)
39
EasyMath
Fibonacci Series — First N Terms
Print the first N terms of the Fibonacci series (starting from 0).
Input 1
7
Output 1
0 1 1 2 3 5 8
Input 2
1
Output 2
0
⚙ Approach Iteratively compute: a, b = 0, 1 then repeatedly a, b = b, a+b.
Python Solution ✔ Verified
n = int(input())
a, b = 0, 1
fib = []
for _ in range(n):
fib.append(a)
a, b = b, a + b
print(*fib)
Time: O(n)Space: O(n)
40
EasyMath
Factorial Without Built-in Function
Given a non-negative integer N, compute N! using a loop (not the math.factorial built-in).
Input 1
5
Output 1
120
Input 2
0
Output 2
1
Input 3
10
Output 3
3628800
⚙ Approach Iteratively multiply from 1 to N. Base case: 0! = 1.
Python Solution ✔ Verified
n = int(input())
result = 1
for i in range(2, n+1):
result *= i
print(result)
Time: O(n)Space: O(1)
41
EasyNumber Theory
Perfect Number Check
A perfect number equals the sum of its proper divisors (all divisors excluding itself). Check if N is perfect.
Input 1
6
Output 1
Yes
Input 2
28
Output 2
Yes
Input 3
12
Output 3
No
⚙ Approach Sum all divisors from 1 to n-1. Compare with n.
Python Solution ✔ Verified
n = int(input())
total = sum(i for i in range(1, n) if n % i == 0)
print("Yes" if total == n else "No")
Time: O(n)Space: O(1)
42
EasyNumber Theory
Convert Decimal to Binary, Octal and Hex
Given a decimal integer N, print its binary, octal, and hexadecimal representations (without prefixes).
Input 1
255
Output 1
11111111 377 ff
Input 2
16
Output 2
10000 20 10
⚙ Approach Use Python built-ins: bin(), oct(), hex() and strip the prefix (0b, 0o, 0x).
Python Solution ✔ Verified
n = int(input())
print(bin(n)[2:], oct(n)[2:], hex(n)[2:])
Time: O(log n)Space: O(log n)
43
MediumNumber Theory
Find All Prime Factors
Given a positive integer N, find and print all its prime factors (with repetition).
Input 1
12
Output 1
2 2 3
Input 2
100
Output 2
2 2 5 5
Input 3
13
Output 3
13
⚙ Approach Divide N by 2 while divisible, then check odd divisors from 3 to sqrt(N).
Python Solution ✔ Verified
n = int(input())
factors = []
d = 2
while d * d <= n:
while n % d == 0:
factors.append(d)
n //= d
d += 1
if n > 1:
factors.append(n)
print(*factors)
Time: O(sqrt(n))Space: O(log n)
44
EasyMath
Power Without Built-in (Fast Exponentiation)
Given base B and exponent E (both non-negative integers), compute B^E without using ** or pow(). Handle E=0 as 1.
Input 1
2 10
Output 1
1024
Input 2
3 0
Output 2
1
Input 3
5 3
Output 3
125
⚙ Approach Exponentiation by squaring: halve E each step. If E is odd, multiply result by base.
Python Solution ✔ Verified
b, e = int(input()), int(input())
result = 1
base = b
while e > 0:
if e % 2 == 1:
result *= base
base *= base
e //= 2
print(result)
Time: O(log e)Space: O(1)
45
EasyMath
Sum of Digits Until Single Digit (Digital Root)
Given a non-negative integer N, repeatedly sum its digits until the result is a single digit. Print the digital root.
Input 1
9875
Output 1
2
Input 2
0
Output 2
0
Input 3
493
Output 3
7
⚙ Approach Digital root formula: if n==0 return 0, else return 1 + (n-1) % 9. This is O(1).
Python Solution ✔ Verified
n = int(input())
print(0 if n == 0 else 1 + (n - 1) % 9)
Time: O(1)Space: O(1)
Section 5
🔎 Sorting & Searching — Q46 to Q50
Sorting & Searching
Sorting problems test algorithmic thinking. TCS sometimes asks you to implement a specific sort from scratch.
46
EasySorting
Bubble Sort Implementation
Implement bubble sort to sort an array of N integers in ascending order without using Python's built-in sort.
Input 1
[64,34,25,12,22,11]
Output 1
11 12 22 25 34 64
Input 2
[3,1,2]
Output 2
1 2 3
⚙ Approach Repeatedly step through the list comparing adjacent elements and swapping if out of order. Repeat N times.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print(*arr)
Time: O(n^2)Space: O(1)
47
EasySearching
Binary Search in Sorted Array
Given a sorted array of N integers and a target T, perform binary search. Print the 0-based index if found, else -1.
Input 1
[1,3,5,7,9,11], T=7
Output 1
3
Input 2
[1,2,3], T=5
Output 2
-1
⚙ Approach Standard binary search: low, high pointers. Mid = (low+high)//2. Adjust based on comparison.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
t = int(input())
low, high, result = 0, n-1, -1
while low <= high:
mid = (low + high) // 2
if arr[mid] == t:
result = mid; break
elif arr[mid] < t:
low = mid + 1
else:
high = mid - 1
print(result)
Time: O(log n)Space: O(1)
48
MediumSorting
Find Kth Largest Element
Given an array of N integers and integer K, find the Kth largest element.
Input 1
[3,2,1,5,6,4], K=2
Output 1
5
Input 2
[3,2,3,1,2,4,5,5,6], K=4
Output 2
4
⚙ Approach Sort in descending order and return element at index K-1. Or use min-heap of size K for O(n log k).
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
k = int(input())
arr.sort(reverse=True)
print(arr[k-1])
Time: O(n log n)Space: O(1)
49
MediumSorting
Merge Two Sorted Arrays
Given two sorted arrays of sizes M and N, merge them into a single sorted array.
Input 1
[1,3,5] [2,4,6]
Output 1
1 2 3 4 5 6
Input 2
[1,2] [3,4]
Output 2
1 2 3 4
⚙ Approach Two-pointer merge: compare front elements of both arrays, pick the smaller one.
Python Solution ✔ Verified
m = int(input())
a = [int(input()) for _ in range(m)]
n = int(input())
b = [int(input()) for _ in range(n)]
i = j = 0
res = []
while i < m and j < n:
if a[i] <= b[j]:
res.append(a[i]); i += 1
else:
res.append(b[j]); j += 1
res.extend(a[i:])
res.extend(b[j:])
print(*res)
Time: O(m+n)Space: O(m+n)
50
MediumSorting
Check if Array Can Be Sorted by Adjacent Swaps (Bubble Sort Passes)
Given an array, determine the minimum number of bubble sort passes needed to fully sort it. Print the count.
Input 1
[1,2,3,4,5]
Output 1
0
Input 2
[5,4,3,2,1]
Output 2
4
Input 3
[1,3,2,4]
Output 3
1
⚙ Approach Simulate bubble sort counting passes. A pass that makes no swaps is the first unnecessary pass.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
passes = 0
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if swapped:
passes += 1
else:
break
print(passes)
Time: O(n^2)Space: O(1)
Section 6
⭐ Pattern Printing — Q51 to Q54
Pattern Printing
Pattern questions test nested loop understanding and appear occasionally in TCS Foundation section.
51
EasyPatterns
Right-Angled Triangle of Stars
Print a right-angled triangle pattern of stars with N rows. Row i has i stars.
Input 1
5
Output 1
*
**
***
****
*****
⚙ Approach For each row i from 1 to N, print i stars.
Python Solution ✔ Verified
n = int(input())
for i in range(1, n+1):
print("*" * i)
Time: O(n^2)Space: O(1)
52
EasyPatterns
Number Pyramid Pattern
Print a number pyramid with N rows. Row i contains numbers 1 to i separated by spaces.
Input 1
4
Output 1
1
1 2
1 2 3
1 2 3 4
⚙ Approach For each row i, print numbers 1 to i.
Python Solution ✔ Verified
n = int(input())
for i in range(1, n+1):
print(*range(1, i+1))
Time: O(n^2)Space: O(1)
53
EasyPatterns
Inverted Star Triangle
Print an inverted right-angled triangle of stars with N rows starting from N stars down to 1.
Input 1
4
Output 1
****
***
**
*
⚙ Approach Loop from N down to 1 printing that many stars per row.
Python Solution ✔ Verified
n = int(input())
for i in range(n, 0, -1):
print("*" * i)
Time: O(n^2)Space: O(1)
54
MediumPatterns
Diamond Pattern
Print a diamond pattern of stars with N rows (N must be odd). The widest row (middle) has N stars.
Input 1
5
Output 1
*
***
*****
***
*
⚙ Approach Print upper half: rows with 1,3,...,N stars with padding. Then lower half: N-2,...,1 stars.
Python Solution ✔ Verified
n = int(input())
for i in range(1, n+1, 2):
print(" " * ((n-i)//2) + "*" * i)
for i in range(n-2, 0, -2):
print(" " * ((n-i)//2) + "*" * i)
Time: O(n^2)Space: O(1)
Section 7
🔄 Recursion & Dynamic Programming — Q55 to Q58
Recursion & Dynamic Programming
These appear in the Advanced coding section. Practise these if you are targeting TCS Digital or higher packages.
55
MediumRecursion
Tower of Hanoi
Given N disks and 3 rods (A, B, C), print all steps to move disks from A to C using B as auxiliary. Rules: only one disk at a time, no larger disk on smaller.
Input 1
2
Output 1
A->C, A->B, C->B
Input 2
3
Output 2
7 moves total
⚙ Approach Recursive: move N-1 disks to auxiliary, move Nth disk to destination, move N-1 from auxiliary to destination.
Python Solution ✔ Verified
def hanoi(n, src, dest, aux):
if n == 1:
print(f"{src}->{dest}")
return
hanoi(n-1, src, aux, dest)
print(f"{src}->{dest}")
hanoi(n-1, aux, dest, src)
n = int(input())
hanoi(n, "A", "C", "B")
Time: O(2^n)Space: O(n)
56
MediumDynamic Programming
Longest Common Subsequence (LCS)
Given two strings S1 and S2, find the length of their Longest Common Subsequence.
Input 1
ABCBDAB BDCABA
Output 1
4
Input 2
AGGTAB GXTXAYB
Output 2
4
⚙ Approach Classic DP: dp[i][j] = LCS length of S1[:i] and S2[:j]. Fill bottom-up. If chars match: dp[i][j] = dp[i-1][j-1]+1.
Python Solution ✔ Verified
s1 = input().strip()
s2 = input().strip()
m, n = len(s1), len(s2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
print(dp[m][n])
Time: O(m*n)Space: O(m*n)
57
MediumDynamic Programming
0/1 Knapsack Problem
Given N items each with weight W[i] and value V[i], and capacity C, find the maximum value that fits. Each item can be used at most once.
Input 1
W=[1,2,3] V=[6,10,12] C=5
Output 1
22
Input 2
W=[2,3,4,5] V=[3,4,5,6] C=5
Output 2
7
⚙ Approach Classic 0/1 knapsack DP. dp[i][w] = max value using first i items with capacity w. Include or exclude each item.
Python Solution ✔ Verified
n, c = int(input()), int(input())
w = list(map(int, input().split()))
v = list(map(int, input().split()))
dp = [[0]*(c+1) for _ in range(n+1)]
for i in range(1, n+1):
for cap in range(c+1):
dp[i][cap] = dp[i-1][cap]
if w[i-1] <= cap:
dp[i][cap] = max(dp[i][cap],
dp[i-1][cap-w[i-1]] + v[i-1])
print(dp[n][c])
Time: O(n*c)Space: O(n*c)
58
MediumRecursion
Count Subsets with Given Sum
Given an array of N non-negative integers and a target sum S, count the number of subsets that sum exactly to S.
Input 1
[1,2,3,4,5] S=5
Output 1
3
Input 2
[3,3,3] S=6
Output 2
3
⚙ Approach Recursive solution: at each element, either include it (subtract from S) or exclude it. Base cases: S==0 → 1 way, no elements → 0 ways.
Python Solution ✔ Verified
def count_subsets(arr, n, s):
if s == 0: return 1
if n == 0: return 0
if arr[n-1] > s:
return count_subsets(arr, n-1, s)
return (count_subsets(arr, n-1, s) +
count_subsets(arr, n-1, s - arr[n-1]))
n = int(input())
arr = list(map(int, input().split()))
s = int(input())
print(count_subsets(arr, n, s))
Time: O(2^n)Space: O(n)
Section 8
🎯 Miscellaneous — Q59 to Q60
Miscellaneous & Logic
These don't fit a neat category but have appeared in real TCS NQT exam slots.
59
EasyMiscellaneous
Caesar Cipher — Encrypt a String
Given a plaintext string and shift K, encrypt using Caesar cipher (shift each letter by K, wrap around). Preserve case and non-alphabetic characters.
Input 1
Hello K=3
Output 1
Khoor
Input 2
xyz K=3
Output 2
abc
⚙ Approach For each character: compute position, apply shift mod 26, convert back. Non-alpha characters stay unchanged.
Python Solution ✔ Verified
text = input()
k = int(input()) % 26
result = []
for c in text:
if c.isalpha():
base = ord('A') if c.isupper() else ord('a')
result.append(chr((ord(c) - base + k) % 26 + base))
else:
result.append(c)
print(''.join(result))
Time: O(n)Space: O(n)
60
EasyMiscellaneous
Leap Year Checker
Given a year Y, determine if it is a leap year. A year is a leap year if divisible by 4, except century years must be divisible by 400.
Input 1
2024
Output 1
Leap Year
Input 2
1900
Output 2
Not Leap Year
Input 3
2000
Output 3
Leap Year
⚙ Approach Rule: (divisible by 4 AND not divisible by 100) OR divisible by 400.
Python Solution ✔ Verified
y = int(input())
if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0):
print("Leap Year")
else:
print("Not Leap Year")
Time: O(1)Space: O(1)
FAQ
Frequently Asked Questions
How many coding questions are asked in TCS NQT? ▼
TCS NQT has 1–2 coding questions in 60–90 minutes. Foundation section: 1 easy-medium problem. Advanced section: 1 harder problem.
What programming languages are allowed in TCS NQT? ▼
Python, Java, C, and C++ are allowed. Python is recommended for faster and cleaner solutions.
Medium difficulty. Story-based problems test logical thinking, not advanced DSA. Knowing arrays, strings, and basic math in Python is sufficient to attempt both questions.
Is there negative marking in TCS NQT coding? ▼
There is no negative marking in the coding section. Partial marks may be awarded based on test cases passed. Always attempt to submit even if your solution is not perfect.
What is TITA in TCS NQT coding? ▼
TITA stands for Type In The Answer. Your code output must exactly match the expected output including spaces and newlines. Always use print() carefully in Python.
Courses
Want Complete TCS NQT Preparation?
Explore all CampusMonk courses — mock tests, recorded programs, and full placement packs.
Top 200 Infosys Verbal Ability Questions SE, DSE & SP Roles — With Answers
200 Actual Questions • 2026 Updated
Top 200 Infosys Verbal Ability Questions SE, DSE & SP Roles — With Answers
Real questions asked in Infosys placement exams — synonyms, antonyms, sentence correction, fill in blanks, reading comprehension and more.
CampusMonkAll 3 Roles CoveredUpdated May 202625 min read
200
Questions
8
Topic Areas
20–25
Qs in Exam
20 min
SE Time Limit
3
Roles Covered
Infosys Roles & Verbal Difficulty
Infosys hires freshers through three tracks. Verbal section difficulty varies by role:
SE Systems Engineer
₹3.36–5 LPA
20 questions in 20 min. Easy to Moderate. Grammar, vocabulary, basic RC.
DSE Digital Specialist Engineer
₹6.5–9 LPA
22–25 questions. Moderate to Hard. Longer RC, complex vocabulary.
SP Specialist Programmer
₹10–21 LPA
Hard. Critical reasoning, inference-based RC and advanced grammar.
⚡ Quick Tip: No negative marking in Infosys verbal. Attempt every question. Eliminate 2 wrong options first — your accuracy will improve significantly.
Section 1
🔵 Synonyms — Q1 to Q30
Synonyms
Select the option closest in meaning to the given word.
Q1 · Synonyms · SE/DSE/SP
HARMONY
A. Concord ✓
B. Corpulent
C. Circumspect
D. Obsolete
Answer: A. Concord. Harmony = a state of agreement. Concord carries the same meaning.
Q2 · Synonyms · SE/DSE/SP
UNWARY
A. Heedless ✓
B. Fearless
C. Vigilant
D. Tired
Answer: A. Heedless. Unwary = not alert to danger. Heedless = reckless lack of care.
Q3 · Synonyms · SE/DSE/SP
MECHANICAL
A. Perfunctory ✓
B. Unusual
C. New
D. Infrequent
Answer: A. Perfunctory. Mechanical (in context) = done as routine without thought. Perfunctory = done with minimal effort.
Q4 · Synonyms · SE/DSE/SP
FALLIBILITY
A. Defective ✓
B. Drop
C. Amicable
D. Proximity
Answer: A. Defective. Fallibility = tendency to make errors. Defective = imperfect or flawed.
The transition to automated processes has been ______, requiring significant workforce retraining.
A. Seamless
B. Disruptive ✓
C. Effortless
D. Irrelevant
Answer: B. Disruptive. Significant retraining signals a disruptive (not seamless) transition.
Q68 · Fill in Blanks · SE
Many women have a ______ detail, and are far more systematic with investment plans.
A. Keen eye in
B. Keen eye for ✓
C. Keen eye at
D. Keen eye on
Answer: B. Keen eye for. The correct idiom is a keen eye for detail.
Q69 · Fill in Blanks · SE/DSE
The government's new policy was met with widespread ______ from the public, forcing a review.
A. Approval
B. Opposition ✓
C. Indifference
D. Celebration
Answer: B. Opposition. Forcing a review implies the policy was not welcomed.
Q70 · Fill in Blanks · DSE/SP
In the era of technology, ______ thinking becomes a paramount skill for informed decisions.
A. Critical ✓
B. Passive
C. Emotional
D. Random
Answer: A. Critical. Critical thinking = analysing and evaluating information.
Q71 · Fill in Blanks · SE
The doctor recommended ______ exercise to help the patient recover from injury.
A. Moderate ✓
B. Extreme
C. Excessive
D. None at all
Answer: A. Moderate. For recovery, doctors recommend moderate exercise.
Q72 · Fill in Blanks · DSE
His argument was so ______ that even the judge was persuaded to reconsider.
A. Compelling ✓
B. Weak
C. Absurd
D. Vague
Answer: A. Compelling. Compelling = evoking strong interest. Strong enough to persuade a judge.
Q73 · Fill in Blanks · SE
She has a ______ for languages and can speak five fluently.
A. Flair ✓
B. Dislike
C. Aversion
D. Resistance
Answer: A. Flair. Flair = special instinctive aptitude. Having a flair for languages explains fluency.
Q74 · Fill in Blanks · SE/DSE
The report was ______ with statistics and data, making it difficult to read.
A. Replete ✓
B. Devoid
C. Empty
D. Lacking
Answer: A. Replete. Replete = filled or well-supplied. The report was full of data.
Q75 · Fill in Blanks · SP
The new system is ______ in design, allowing different modules to be integrated seamlessly.
A. Modular ✓
B. Rigid
C. Archaic
D. Isolated
Answer: A. Modular. Modular = designed with standardised units for flexibility.
Q76 · Fill in Blanks · SE
The ______ of the agreement was hailed as a diplomatic achievement.
A. Ratification ✓
B. Rejection
C. Cancellation
D. Postponement
Answer: A. Ratification. Ratification = formal approval. A diplomatic achievement implies approval.
Q77 · Fill in Blanks · SE/DSE
Despite the team's ______ efforts, they failed to complete the project on time.
A. Herculean ✓
B. Minimal
C. Careless
D. Lazy
Answer: A. Herculean. Herculean = requiring great strength or effort.
Q78 · Fill in Blanks · SE
The company was forced to ______ its expansion plans due to financial constraints.
A. Shelve ✓
B. Accelerate
C. Publicise
D. Complete
Answer: A. Shelve. To shelve a plan = to set it aside indefinitely.
Q79 · Fill in Blanks · DSE
The scientist's theory was initially met with ______ but later gained universal acceptance.
A. Scepticism ✓
B. Enthusiasm
C. Celebration
D. Indifference
Answer: A. Scepticism. Initially met with scepticism (doubt) but later accepted.
Q80 · Fill in Blanks · SE
The artist's work was so ______ that viewers could not agree on what it meant.
A. Ambiguous ✓
B. Clear
C. Simple
D. Literal
Answer: A. Ambiguous. Ambiguous = open to multiple interpretations.
Q81 · Fill in Blanks · SE
The lawyer spoke with great ______, convincing the jury with every word.
A. Eloquence ✓
B. Confusion
C. Hesitation
D. Arrogance
Answer: A. Eloquence. Eloquence = fluent persuasive speaking.
Q82 · Fill in Blanks · SE/DSE
The teacher's explanation was ______ enough for even the weakest students to understand.
A. Lucid ✓
B. Vague
C. Complex
D. Ambiguous
Answer: A. Lucid. Lucid = clear and easy to understand.
Q83 · Fill in Blanks · DSE
The merger was ______ at first, but eventually proved beneficial for both companies.
A. Controversial ✓
B. Celebrated
C. Ignored
D. Unopposed
Answer: A. Controversial. Controversial at first but beneficial later is the classic contrast pattern.
Q84 · Fill in Blanks · SE
The children were ______ with joy when they heard about the school trip.
A. Elated ✓
B. Disappointed
C. Confused
D. Anxious
Answer: A. Elated. Elated = very happy or joyful.
Q85 · Fill in Blanks · SP
The startup's innovative approach was seen as a ______ to the traditional industry model.
A. Disruption ✓
B. Confirmation
C. Reinforcement
D. Continuation
Answer: A. Disruption. An innovative approach that challenges a traditional model is a disruption.
Section 4
🟡 Sentence Correction — Q86 to Q110
Sentence Correction
Choose the option that corrects the underlined part. Select No correction required if already correct.
Q86 · Sentence Correction · SE
The president called out to his people to see if they make sacrifices for the good of their country.
A. Called on his people to see if they make sacrifices ✓
B. Called upon his people to see and make sacrifices
C. Called upon his people to make sacrifices
D. Called for his people to make sacrifices
Answer: A. Called on his people to see if they make sacrifices. Called on = to request. The president is checking IF people make sacrifices.
Q87 · Sentence Correction · SE
Airlines that still make the pilots pay to their training will find it difficult to fill vacancies.
A. make the pilots pay to their training
B. make the pilots pay for their training ✓
C. make the pilots pay with their training
D. make the pilots paying for their training
Answer: B. make the pilots pay for their training. Pay for is the correct preposition. You pay for a course or training.
Q88 · Sentence Correction · SE/DSE
The transit of the Planet of Love happen in pairs, eight years apart every century.
A. The transits of the Planet of Love happen in pairs
B. The transit of the Planet of Love happens in pairs ✓
C. No correction required
D. The transit happens in pairs of the Planet
Answer: B. The transit of the Planet of Love happens in pairs. Planet of Love = Venus (singular). Verb must be singular: happens.
Q89 · Sentence Correction · SE
Jane was asked by her aunt, "Where were you last night".
A. aunt that, "Where were you last night?"
B. No correction required
C. aunt, "Where had you been last night."
D. aunt, "Where were you last night?" ✓
Answer: D. aunt, "Where were you last night?". Direct question needs a question mark at the end.
Q90 · Sentence Correction · SE/DSE
The government appears to be at war with it's own people.
A. No correction required
B. to be at war against it's own people
C. to be at war with its own people ✓
D. to be on war with it's own people
Answer: C. to be at war with its own people. It's = it is (contraction). Need possessive its (no apostrophe).
Q91 · Sentence Correction · SE
This bridge neither crossed the Thames, and neither gave access to a lost island in the river.
A. This bridge either crossed the Thames, and nor gave
B. This bridge neither crossed the Thames, and nor gives
C. No correction required
D. This bridge either crossed the Thames, or gave ✓
Answer: D. This bridge either crossed the Thames, or gave. Neither...nor = none of two. Either...or = any one of two. Use either...or here.
Q92 · Sentence Correction · SE/DSE
It is a more difficult task to learn to type than mastering a simple word processing program.
A. than mastering
B. than to master ✓
C. than mastered
D. No correction required
Answer: B. than to master. Parallel structure: to learn to type must be paired with to master (both infinitives).
Q93 · Sentence Correction · SE
He is one of the best players who has ever played for this team.
A. who has
B. who have ✓
C. who is
D. No correction required
Answer: B. who have. One of the best players: relative clause refers to players (plural). Use who have.
Q94 · Sentence Correction · SE/DSE
Neither the manager nor the employees was satisfied with the decision.
A. was
B. were ✓
C. is
D. No correction required
Answer: B. were. With neither...nor, verb agrees with the noun closer to it. Employees (plural) = were.
Q95 · Sentence Correction · SE
She has been working in this company since five years.
A. has been working
B. has worked ✓
C. is working
D. No correction required
Answer: B. has worked. Since with period of time uses present perfect simple: has worked.
Q96 · Sentence Correction · SE
Between you and I, this deal is not in the company's best interest.
A. I
B. me ✓
C. myself
D. No correction required
Answer: B. me. After a preposition (between), use object pronouns: between you and me.
Q97 · Sentence Correction · SE
She is more smarter than her sister.
A. more smarter
B. smarter ✓
C. most smart
D. No correction required
Answer: B. smarter. Never use more with a comparative adjective ending in -er. Say smarter.
Q98 · Sentence Correction · SE/DSE
He doesn't knows the answer to this question.
A. doesn't know ✓
B. don't knows
C. does not knew
D. No correction required
Answer: A. doesn't know. After does/doesn't, the main verb takes its base form. Knows becomes know.
Q99 · Sentence Correction · SE
The manager, along with his team, are attending the conference.
A. is attending ✓
B. were attending
C. have been attending
D. No correction required
Answer: A. is attending. The manager is the subject. Along with his team is parenthetical. Use is (singular).
Q100 · Sentence Correction · DSE/SP
If I would have known about the meeting, I would have attended it.
A. would have known
B. had known ✓
C. would know
D. No correction required
Answer: B. had known. Third conditional: if-clause takes past perfect. If I had known... I would have attended.
Q101 · Sentence Correction · SE
Neither I nor my friends was informed about the change.
A. was
B. were ✓
C. is
D. No correction required
Answer: B. were. Neither...nor: verb agrees with the noun closer to it. Friends (plural) = were.
Q102 · Sentence Correction · SE/DSE
She insists to go to the party tonight.
A. insists to go
B. insists on going ✓
C. insists going
D. No correction required
Answer: B. insists on going. Insist is followed by preposition on and gerund: insist on going.
Q103 · Sentence Correction · SE/DSE
Each of the students have submitted their assignment.
A. has submitted ✓
B. have submitted
C. had been submitting
D. No correction required
Answer: A. has submitted. Each always takes a singular verb: has submitted.
Q104 · Sentence Correction · DSE
The phenomenon are being investigated by top scientists.
A. is being investigated ✓
B. are being investigated
C. were being investigated
D. No correction required
Answer: A. is being investigated. Phenomenon is singular; phenomena is plural. Use is being investigated.
Q105 · Sentence Correction · SE
I am looking forward to meet you at the conference.
A. to meet
B. to meeting ✓
C. to have met
D. No correction required
Answer: B. to meeting. Look forward to is followed by a gerund: looking forward to meeting you.
Q106 · Sentence Correction · SE/DSE
No sooner had she finished speaking than the audience burst into applause.
A. No correction required ✓
B. when
C. while
D. as soon as
Answer: A. No correction required. No sooner...than is the correct fixed expression. No error.
Q107 · Sentence Correction · SE
The teacher as well as students were present in the hall.
A. was present ✓
B. were present
C. have been present
D. No correction required
Answer: A. was present. The teacher (singular) is the subject. Use was present. As well as is parenthetical.
Q108 · Sentence Correction · SE
Unless you will not work harder, you will not pass the examination.
A. Unless you will not
B. Unless you work ✓
C. Unless you had
D. No correction required
Answer: B. Unless you work. Unless already contains a negative meaning. Adding not creates a double negative.
Q109 · Sentence Correction · SE/DSE
Five hundred rupees are not enough to buy a laptop.
A. is ✓
B. are
C. were
D. No correction required
Answer: A. is. Sums of money are treated as singular: Five hundred rupees is not enough.
Q110 · Sentence Correction · SE
She is good in singing and dancing.
A. good at ✓
B. good in
C. good for
D. No correction required
Answer: A. good at. The correct preposition is good at (not good in).
Section 5
🟡 Error Detection — Q111 to Q130
Error Detection
The sentence is divided into parts (A)(B)(C)(D). Identify the part with a grammatical error, or select No Error.
Q111 · Error Detection · SE
Hong Kong has been endowed (A) / with one of the finest natural (B) / harbour in the world. (C) / No error (D)
A. Hong Kong has been endowed
B. with one of the finest natural
C. harbour in the world ✓
D. No error
Answer: C. harbour in the world. One of must be followed by a plural noun. Correct: harbours.
Q112 · Error Detection · SE/DSE
Angered over the delay (A) / factory workers shouted (B) / slogans against the President (C) / when he reaches the office. (D)
A. Angered over the delay
B. factory workers shouted
C. slogans against the President
D. when he reaches the office ✓
Answer: D. when he reaches the office. The sentence is in past tense. Reaches should be reached.
Q113 · Error Detection · SE
The phenomena currently under investigation (A) / by the renowned scientist concerns (B) / the interactions of (C) / laser light with biological materials. (D)
A. The phenomena ✓
B. by the renowned scientist concerns
C. the interactions of
D. No error
Answer: A. The phenomena. Phenomena is plural; phenomenon is singular. Since concerns (singular) is used, subject should be phenomenon.
Q114 · Error Detection · SE/DSE
It is a more difficult (A) / task to learn to type than mastering (B) / a simple (C) / word processing program. (D)
A. It is a more difficult
B. task to learn to type than mastering ✓
C. a simple
D. No error
Answer: B. task to learn to type than mastering. Parallel structure: to learn to type than to master. Both must be infinitives.
Q115 · Error Detection · SE
No less than twenty persons (A) / were killed in (B) / the air crash. (C) / No error (D)
A. No less than twenty persons ✓
B. were killed in
C. the air crash
D. No error
Answer: A. No less than twenty persons. For countable items, no fewer than is preferred. Also persons is better as people here.
Q116 · Error Detection · SE
Volunteers of an NGO (A) / interacted with school students (B) / to spread awareness about (C) / environment related issues. (D)
A. Volunteers of an NGO
B. interacted with school students
C. to spread awareness about
D. environment related issues ✓
Answer: D. environment related issues. Compound adjectives before a noun need a hyphen: environment-related issues.
Q117 · Error Detection · SE/DSE
An independent enquiry headed by (A) / Anthony White QC in 2011 further examined (B) / the claims but also exonerated Coucher. (C) / No error (D)
A. An independent enquiry headed by
B. Anthony White QC in 2011 further examined
C. the claims but also exonerated Coucher ✓
D. No error
Answer: C. the claims but also exonerated Coucher. A comma is needed after claims before but.
Q118 · Error Detection · SE
She asked me (A) / that would I (B) / help her with (C) / the project. (D)
A. She asked me
B. that would I ✓
C. help her with
D. No error
Answer: B. that would I. In reported speech, that would I should be whether I would.
Q119 · Error Detection · DSE/SP
Despite of working hard (A) / he could not (B) / pass the examination (C) / in the first attempt. (D)
A. Despite of working hard ✓
B. he could not
C. pass the examination
D. No error
Answer: A. Despite of working hard. Despite is never followed by of. Correct: Despite working hard.
Q120 · Error Detection · SE
He has been (A) / living in Mumbai (B) / for the last twenty years, (C) / isn't he? (D)
A. He has been
B. living in Mumbai
C. for the last twenty years
D. isn't he? ✓
Answer: D. isn't he?. Has been living: question tag must match. Correct: hasn't he?
Q121 · Error Detection · SE
The number of students who (A) / are absent from class (B) / have increased (C) / this month. (D)
A. The number of students who
B. are absent from class
C. have increased ✓
D. No error
Answer: C. have increased. The number of takes a singular verb. Correct: has increased.
Q122 · Error Detection · SE
He was (A) / confident that he (B) / will succeed (C) / in the interview. (D)
A. He was
B. confident that he
C. will succeed ✓
D. No error
Answer: C. will succeed. Main clause is past (was), so reported clause should also be past: would succeed.
Q123 · Error Detection · SE/DSE
One should not boast (A) / of his achievements (B) / before others. (C) / No error. (D)
A. One should not boast
B. of his achievements ✓
C. before others
D. No error
Answer: B. of his achievements. One should be followed by one's not his. Correct: of one's achievements.
Q124 · Error Detection · SE
He was (A) / confident that (B) / all will go (C) / well. (D)
A. He was
B. confident that
C. all will go ✓
D. No error
Answer: C. all will go. Main clause past tense: should be all would go well.
Q125 · Error Detection · DSE
I often feel I am an outsider (A) / when it comes to my interests (B) / most of my friends (C) / are not fond with classical music. (D)
A. I often feel I am an outsider
B. when it comes to my interests
C. most of my friends
D. are not fond with classical music ✓
Answer: D. are not fond with classical music. The correct phrase is fond of not fond with.
Q126 · Error Detection · SE
The boy (A) / fell of (B) / the bicycle (C) / and hurt himself. (D)
A. The boy
B. fell of ✓
C. the bicycle
D. No error
Answer: B. fell of. The correct preposition is off not of. Correct: fell off the bicycle.
Q127 · Error Detection · SE
I want to (A) / lay down for (B) / a while before (C) / the meeting. (D)
A. I want to
B. lay down ✓
C. a while before
D. No error
Answer: B. lay down. Lay requires an object. Lie down (intransitive) is correct when the subject reclines.
Q128 · Error Detection · SE
Hardly had he entered the room (A) / than the lights (B) / went out. (C) / No error (D)
A. Hardly had he entered the room
B. than the lights ✓
C. went out
D. No error
Answer: B. than the lights. Hardly...when is the correct structure. Hardly...than is incorrect.
Q129 · Error Detection · DSE/SP
I had barely (A) / gone to sleep (B) / when the phone (C) / had rung. (D)
A. I had barely
B. gone to sleep
C. when the phone
D. had rung ✓
Answer: D. had rung. Barely...when: the second event should be in simple past. Correct: when the phone rang.
Q130 · Error Detection · SE
He said that (A) / he has been (B) / waiting for (C) / two hours. (D)
A. He said that
B. he has been ✓
C. waiting for
D. No error
Answer: B. he has been. Said that (past) should be followed by past perfect continuous: he had been waiting.
Section 6
🟢 Reading Comprehension — Q131 to Q165
Reading Comprehension
Read each passage carefully then answer the questions. Tip: Read questions first, then find answers in the passage.
Passage 1 — Gender & Communication (SE / DSE)
Although there is great variation within each gender, on average men and women discuss a surprisingly different range of topics. Studies show women and men from seventeen to eighty discussed different topics with same-sex friends. Common topics included work, movies and television. Female friends spent more time on personal and domestic subjects, relationships, family, health, weight, food and clothing. Men preferred music, current events, sports and business. Women gossiped about close friends and family; men about sports figures and media personalities. These differences can lead to frustration when men and women try to converse.
In the era of technology, where information is abundant, critical thinking becomes a paramount skill. The ability to analyze, evaluate, and synthesize information is crucial for making informed decisions. Technology has given us access to an unprecedented volume of data, but without the capacity to think critically, this abundance can be overwhelming and even misleading. Schools increasingly recognise that teaching students how to think — rather than what to think — is the core mission of modern education.
Passage 3 — Media & Public Trust (DSE / SP)
The decline of the news media's role as a public trust has affected its obligations to civil society. Journalists share a strong conviction that market pressures are undermining the quality of journalism; as news organisations preserve high profit levels by reducing news-gathering resources and neglecting journalism in the public interest, the fundamental role of the press to inform and empower citizens is endangered. A free and independent press is essential to human liberty.
Passage 4 — Library Scheme in India (SE)
The process of accessing books under the library scheme is quite long and cumbersome, and payments are made very late. As a result a large number of publishers do not choose to apply under the scheme. We should revise the scheme and make it attractive and meaningful. We should also arrange regular orientation courses for librarians and frame comprehensive library regulations in each state.
Q131 · Reading Comprehension · SE
[Passage 1 — Gender & Communication] According to the passage, which of the following is INCORRECT?
A. Work, movies and TV are common topics for both
B. Women like to gossip while men do not ✓
C. Men are more inclined towards sports and business
D. Men and women discuss a different range of topics
Answer: B. Women like to gossip while men do not. The passage says men DO gossip — about sports figures. Option B incorrectly claims men do not gossip at all.
Q132 · Reading Comprehension · SE
[Passage 1] After what age does the range of topics that each gender finds interesting start to differ?
A. 17 ✓
B. 22
C. 43
D. 50
Answer: A. 17. The passage states: women and men ranging in age from seventeen to eighty.
Q133 · Reading Comprehension · DSE
[Passage 1] What can be inferred from 'these differences can lead to frustration when men and women try to converse'?
A. Men and women should not converse
B. Communication gaps exist due to different interests ✓
C. Women are better communicators
D. Only work topics are safe in mixed conversations
Answer: B. Communication gaps exist due to different interests. Different topic preferences create communication gaps.
Q134 · Reading Comprehension · SE
[Passage 2 — Technology & Critical Thinking] What is the best summary of this passage?
A. Technology has made critical thinking obsolete
B. Critical thinking is essential in the age of technology ✓
C. Abundant information has diminished critical thinking
D. Technology has limited the need for critical thinking
Answer: B. Critical thinking is essential in the age of technology. The passage highlights the importance of critical thinking in the technology era.
Q135 · Reading Comprehension · DSE
[Passage 2] What does the author mean by 'teaching how to think rather than what to think'?
A. Schools should stop teaching facts
B. Developing reasoning skills matters more than memorising content ✓
C. Students should question every fact
D. Technology should replace teachers
Answer: B. Developing reasoning skills matters more than memorising content. How to think = reasoning skills. What to think = memorising information.
Q136 · Reading Comprehension · DSE
[Passage 3 — Media & Public Trust] What is the primary threat to quality journalism?
A. Lack of talented journalists
B. Market pressures that reduce news-gathering resources ✓
C. Government censorship
D. Readers not buying newspapers
Answer: B. Market pressures that reduce news-gathering resources. The passage explicitly states: market pressures are undermining journalism.
Q137 · Reading Comprehension · SP
[Passage 3] What does the author imply by 'a free and independent press is essential to human liberty'?
A. Press freedom guarantees economic prosperity
B. Only journalists should have freedom of expression
C. Democracy and civil liberty depend on an unbiased free press ✓
D. News media should be managed by the government
Answer: C. Democracy and civil liberty depend on an unbiased free press. Human liberty = civil rights and democratic freedoms.
Q138 · Reading Comprehension · SE
[Passage 4 — Library Scheme] What is the primary purpose of this passage?
A. Discuss the importance of books
B. Discuss the spread of library facilities
C. Discuss the reluctance of reading
D. Discuss the neglect of libraries by people and authorities ✓
Answer: D. Discuss the neglect of libraries by people and authorities. The passage discusses how the library scheme is dysfunctional.
Q139 · Reading Comprehension · DSE
[Passage 4] What can be inferred about publishers?
A. They avoid the scheme because of procedural inefficiency ✓
B. Libraries are maintained but people do not read
C. Publishers prefer digital over print
D. There are too many publishers in India
Answer: A. They avoid the scheme because of procedural inefficiency. Long process and late payments cause publishers to not apply.
Q140 · RC Inference · DSE/SP
A passage says: 'Despite repeated setbacks, the scientist never abandoned her research. Colleagues admired her tenacity.' What quality is highlighted?
Which best describes the main idea of a passage discussing how urban farming reduces carbon footprints by cutting food transportation distances?
A. Urban farming contributes to environmental sustainability ✓
B. All cities should ban traditional farming
C. Transportation is the main cause of global warming
D. Farming should be restricted to rural areas only
Answer: A. Urban farming contributes to environmental sustainability. The central argument is that urban farming is a sustainable environmental practice.
Q142 · RC Tone · DSE
A passage strongly critiques government inaction on climate change using phrases like 'criminal negligence' and 'irreversible damage.' The tone is best described as:
A. Indignant ✓
B. Neutral
C. Celebratory
D. Sarcastic
Answer: A. Indignant. Indignant = feeling anger about perceived unfair treatment.
Q143 · RC Vocabulary · SE/DSE
In 'The legislation was seen as a panacea for the country's economic woes,' PANACEA most closely means:
A. Problem
B. Universal cure ✓
C. Partial solution
D. Controversial decision
Answer: B. Universal cure. Panacea = a solution or remedy for all difficulties or diseases.
Q144 · RC Inference · SE
Passage: 'The CEO gave bonuses to every employee and publicly praised the team. Morale soared.' What can you infer?
A. Recognition and reward improve employee motivation ✓
B. Employees only care about money
C. Public praise always causes morale problems
D. The company was facing a loss
Answer: A. Recognition and reward improve employee motivation. Bonuses and public praise led to soaring morale.
Q145 · RC Detail · SE
Passage: 'Only 30% of plastic waste is recycled globally. The rest ends up in landfills or oceans.' Where does most unrecycled plastic end up?
A. Landfills or oceans ✓
B. Recycling plants
C. Energy generation facilities
D. Compost sites
Answer: A. Landfills or oceans. Directly stated: the rest ends up in landfills or oceans.
Q146 · RC Purpose · DSE
A passage presents multiple perspectives on AI replacing jobs without favouring one side. The author's purpose is most likely to:
A. Present a balanced analysis of the AI-employment debate ✓
B. Argue that AI is harmful
C. Convince readers to support AI development
D. Entertain readers with AI stories
Answer: A. Present a balanced analysis of the AI-employment debate. Multiple perspectives without a conclusion = balanced analytical approach.
Q147 · RC Vocabulary · SE
'The critics were ACERBIC in their reviews of the film.' ACERBIC most nearly means:
A. Complimentary
B. Sharply critical ✓
C. Neutral
D. Enthusiastic
Answer: B. Sharply critical. Acerbic = sharp and forthright in a way that shows critical disapproval.
Q148 · RC Assumption · DSE/SP
Statement: 'Who rises from prayer a better man, his prayer is answered.' Assumption: Prayers make a man more human. Is this assumption implicit?
A. Yes, implicit
B. No, not implicit ✓
C. Cannot be determined
D. Partially implicit
Answer: B. No, not implicit. The statement focuses on personal improvement. Whether prayers make one more human is not implied.
Q149 · RC Inference · SE
Passage: 'Solar panels have become 89% cheaper since 2010.' What can be inferred?
A. Solar energy is becoming more accessible and affordable ✓
B. Solar panels are now free
C. All homes should install solar panels
D. Traditional energy is more popular now
Answer: A. Solar energy is becoming more accessible and affordable. An 89% cost reduction means solar energy is increasingly accessible.
Q150 · RC Detail · SE/DSE
Passage: 'The rise of remote work has blurred the boundary between professional and personal life, leading to burnout.' Which conclusion is best supported?
A. Remote work should be banned
B. Remote work without boundaries negatively affects well-being ✓
C. Office work is always better
D. Burnout only affects remote workers
Answer: B. Remote work without boundaries negatively affects well-being. The absence of work-life boundaries (not remote work itself) causes burnout.
Q151 · RC Inference · DSE
A passage concludes: 'Students who ask questions consistently outperform those who passively absorb information.' What does this imply?
A. Questions waste classroom time
B. Active engagement leads to better academic outcomes ✓
C. Teachers should ask all questions
D. Passive students should be punished
Answer: B. Active engagement leads to better academic outcomes. Students who ask questions = active engagement = better outcomes.
Q152 · RC Vocabulary · SE/DSE
'The politician's speech was deliberately OBFUSCATORY, leaving the audience confused.' OBFUSCATORY means:
A. Clear and direct
B. Intentionally confusing ✓
C. Emotionally moving
D. Factually incorrect
Answer: B. Intentionally confusing. Obfuscatory = designed to obscure understanding; deliberately confusing.
Q153 · RC Summary · SE
A passage discusses how rising inflation leads to decreased consumer spending which slows economic growth. The best one-sentence summary is:
A. Inflation always leads to economic growth
B. Consumer spending has no relation to inflation
C. Inflation reduces consumer spending and slows economic growth ✓
D. Government intervention can always stop inflation
Answer: C. Inflation reduces consumer spending and slows economic growth. Directly summarises the causal chain: inflation reduces spending, slowing growth.
Q154 · RC Detail · SE
Passage: 'The Amazon rainforest produces 20% of the world's oxygen and is home to 10% of all species on Earth.' Which statement is directly supported?
A. The Amazon should be converted to farmland
B. The Amazon is critical to global biodiversity and oxygen production ✓
C. 90% of species live outside the Amazon
D. Oxygen production is declining worldwide
Answer: B. The Amazon is critical to global biodiversity and oxygen production. Directly supported by both facts stated.
Q155 · RC Inference · DSE/SP
A passage describes how a company saw 20% productivity increase after implementing a four-day work week. Which inference is most justified?
A. All companies must adopt four-day work weeks immediately
B. Reduced hours can increase productivity if employees are well-rested ✓
C. Four-day weeks only work in large companies
D. Employees work harder when paid less
Answer: B. Reduced hours can increase productivity if employees are well-rested. Correlation between reduced hours and increased productivity: rest improves output.
Q156 · RC Tone · SE
A passage uses phrases like 'unfortunately', 'it is deeply troubling', and 'we must act now.' The tone is best described as:
A. Optimistic
B. Concerned and urgent ✓
C. Satirical
D. Indifferent
Answer: B. Concerned and urgent. Words like unfortunately and deeply troubling signal concern. Must act now signals urgency.
Q157 · RC Detail · SE/DSE
Passage: 'Mahatma Gandhi led the Salt March in 1930 to protest British salt laws.' What was the purpose?
A. To celebrate Indian culture
B. To protest British taxation on salt ✓
C. To demand military independence
D. To promote trade with Britain
Answer: B. To protest British taxation on salt. Directly stated: to protest British salt laws.
Q158 · RC Inference · DSE
A passage states: 'Countries that invest more in primary education have higher GDP per capita two decades later.' What inference is most reasonable?
A. GDP grows instantly after education investment
B. Education investment leads to long-term economic development ✓
C. Only primary education matters for economic growth
D. GDP is not related to education at all
Answer: B. Education investment leads to long-term economic development. Two decades later suggests a long-term effect of education investment.
Q159 · RC Summary · SE
A passage describes how social media connects people globally but also spreads misinformation rapidly. The best title would be:
A. The Benefits of Social Media
B. Social Media: A Double-Edged Sword ✓
C. Why Social Media Should Be Banned
D. How to Use Social Media Effectively
Answer: B. Social Media: A Double-Edged Sword. Double-edged sword captures both the benefit (connection) and drawback (misinformation).
Q160 · RC Detail · SE
Passage: 'India is the world's largest democracy with over 900 million eligible voters.' Which is directly supported?
A. India has the largest military in Asia
B. India has over 900 million eligible voters ✓
C. India's population is 900 million
D. India has the most political parties
Answer: B. India has over 900 million eligible voters. Directly stated in the passage.
Q161 · RC Vocabulary · DSE/SP
'The author's prose was LAPIDARY — precise, polished, and gem-like in its clarity.' LAPIDARY most nearly means:
A. Vague and informal
B. Extremely long-winded
C. Precise and elegantly concise ✓
D. Scientifically accurate
Answer: C. Precise and elegantly concise. Lapidary (from Latin lapis = stone) = concise and brilliantly crafted.
Q162 · RC Assumption · SP
Statement: 'The government should invest more in mental health infrastructure.' Which assumption is implicit?
A. Mental health is currently adequately funded
B. Mental health infrastructure is currently insufficient ✓
C. Physical health is less important than mental health
D. Only governments can solve mental health crises
Answer: B. Mental health infrastructure is currently insufficient. The recommendation to invest more implies current investment is insufficient.
Q163 · RC Detail · SE
Passage: 'Antibiotics should not be used to treat viral infections. Overuse contributes to antimicrobial resistance.' What is the author warning against?
A. Using too many vitamins
B. Misusing antibiotics for viral infections ✓
C. Ignoring bacterial infections
D. Reducing hospital budgets
Answer: B. Misusing antibiotics for viral infections. Directly supported: using antibiotics for viral infections is the specific misuse warned against.
Q164 · RC Inference · SE/DSE
A passage describes how students in Finland have shorter school days but consistently top global rankings. What can be inferred?
A. Longer school days are always better
B. Quality of instruction matters more than duration ✓
C. Finnish students study privately for more hours
D. Global education rankings are unreliable
Answer: B. Quality of instruction matters more than duration. Shorter days + top rankings = quality of instruction is the differentiating factor.
Q165 · RC Main Idea · DSE/SP
A passage argues that while technology has made life convenient, it has simultaneously increased social isolation, anxiety, and screen addiction. The main idea is:
A. Technology should be banned
B. Technology has brought convenience but also significant social costs ✓
C. Convenience is the most important goal of technology
D. Social media alone is responsible for all mental health issues
Answer: B. Technology has brought convenience but also significant social costs. Acknowledges both benefits (convenience) and costs (isolation, anxiety).
Section 7
🔵 Para Jumbles — Q166 to Q180
Para Jumbles
Arrange the given sentences into a logical, coherent paragraph. Find the opening sentence first.
Q166 · Para Jumble · SE
Arrange: (P) He decided to pursue art despite opposition. (Q) As a young man, he was passionate about painting. (R) Today his works are exhibited in galleries worldwide. (S) His family wanted him to become an engineer.
A. P-Q-S-R
B. Q-S-P-R ✓
C. S-Q-P-R
D. R-P-S-Q
Answer: B. Q-S-P-R. Q introduces character and passion. S introduces conflict. P shows decision. R is the outcome.
Q167 · Para Jumble · SE/DSE
(P) This leads to poor decision-making. (Q) When employees are not heard, morale drops. (R) Companies that ignore feedback stagnate. (S) Low morale results in high attrition.
A. R-Q-S-P ✓
B. Q-P-S-R
C. P-Q-R-S
D. S-R-Q-P
Answer: A. R-Q-S-P. R states the premise. Q gives first consequence. S gives second consequence. P gives the impact.
Q168 · Para Jumble · SE
(P) Readers must therefore approach news critically. (Q) Social media has made it easier to spread false information. (R) Not all content shared online is verified. (S) This has had a profound impact on public opinion.
A. P-Q-R-S
B. Q-S-R-P ✓
C. R-S-P-Q
D. S-Q-P-R
Answer: B. Q-S-R-P. Q introduces the topic. S shows its effect. R elaborates the problem. P offers the solution.
Q169 · Para Jumble · DSE/SP
(P) It is therefore crucial to invest in renewable energy. (Q) Fossil fuels are finite and cause significant environmental damage. (R) Climate change poses an existential threat. (S) Transitioning to renewables could mitigate these effects significantly.
A. R-Q-S-P ✓
B. Q-P-R-S
C. S-R-P-Q
D. P-S-Q-R
Answer: A. R-Q-S-P. R establishes the broad threat. Q explains the problem with current energy. S introduces the solution. P calls to action.
Q170 · Para Jumble · SE
(P) The results confirmed what many had suspected. (Q) A team of scientists conducted a two-year study. (R) They published their findings in a peer-reviewed journal. (S) It focused on the effects of screen time on children's sleep.
A. P-Q-R-S
B. Q-S-P-R ✓
C. R-P-Q-S
D. S-Q-P-R
Answer: B. Q-S-P-R. Q introduces scientists. S explains the focus. P states the results. R is the final outcome.
Q171 · Para Jumble · SE/DSE
(P) She ultimately won the gold medal. (Q) She trained for twelve hours a day. (R) The athlete had always dreamed of the Olympics. (S) Her dedication paid off at the World Championship.
A. R-Q-S-P ✓
B. Q-R-S-P
C. P-Q-S-R
D. S-R-Q-P
Answer: A. R-Q-S-P. R = dream. Q = effort. S = recognition. P = ultimate result.
Q172 · Para Jumble · SE
(P) This is a skill that takes years to develop. (Q) Effective leaders know how to motivate others. (R) They also know when to step back and delegate. (S) Leadership is more than just giving orders.
A. S-Q-R-P ✓
B. Q-S-P-R
C. R-Q-S-P
D. P-R-Q-S
Answer: A. S-Q-R-P. S defines leadership. Q and R describe skills. P concludes by noting it takes time.
Q173 · Para Jumble · DSE/SP
(P) Without access to clean water, communities face severe health risks. (Q) Water scarcity is one of the most pressing global challenges. (R) Governments must prioritise water conservation. (S) Millions lack access to safe drinking water.
A. Q-S-P-R ✓
B. S-P-Q-R
C. P-R-S-Q
D. R-P-Q-S
Answer: A. Q-S-P-R. Q introduces the challenge. S gives the scale. P explains the consequence. R proposes the solution.
Q174 · Para Jumble · SE
(P) However, with the right support they can overcome these obstacles. (Q) First-generation college students face unique challenges. (R) Many lack financial resources and mentorship. (S) Universities must create inclusive support programmes.
A. Q-R-P-S ✓
B. P-Q-R-S
C. R-Q-S-P
D. S-P-Q-R
Answer: A. Q-R-P-S. Q introduces the group. R explains challenges. P provides hope. S gives the institutional call to action.
Q175 · Para Jumble · SE/DSE
(P) Meditation has been linked to reduced anxiety and improved focus. (Q) More people are incorporating mindfulness into daily routines. (R) Scientific studies continue to support these benefits. (S) It appears the mind responds well to deliberate calm.
A. Q-P-R-S ✓
B. P-Q-S-R
C. R-S-Q-P
D. S-P-R-Q
Answer: A. Q-P-R-S. Q introduces the trend. P gives a specific benefit. R adds scientific backing. S draws a broad conclusion.
Q176 · Para Jumble · DSE
(P) The invention of the printing press transformed the spread of knowledge. (Q) Before it, books were rare and expensive. (R) Gutenberg's press democratised access to information. (S) This laid the groundwork for the Renaissance.
A. P-Q-R-S ✓
B. Q-P-S-R
C. R-Q-P-S
D. P-R-Q-S
Answer: A. P-Q-R-S. P introduces the invention. Q explains pre-press context. R gives the democratising effect. S shows historical consequences.
Q177 · Para Jumble · SE
(P) As a result, many industries are rethinking their business models. (Q) The shift to remote work was accelerated by the global pandemic. (R) Companies discovered productivity did not necessarily decline outside the office. (S) This finding challenged decades of traditional workplace assumptions.
A. Q-R-S-P ✓
B. R-Q-S-P
C. P-Q-R-S
D. S-R-Q-P
Answer: A. Q-R-S-P. Q establishes context. R presents the key discovery. S gives the significance. P shows the consequence.
Q178 · Para Jumble · SE/DSE
(P) Biodiversity loss threatens the stability of these ecosystems. (Q) Ecosystems depend on a delicate balance of species interactions. (R) Conservation efforts must target the root causes of habitat destruction. (S) Human activities like deforestation are the primary drivers.
A. Q-P-S-R ✓
B. P-Q-R-S
C. S-Q-P-R
D. R-S-P-Q
Answer: A. Q-P-S-R. Q introduces ecosystems and balance. P identifies the threat. S explains human causes. R proposes the solution.
Q179 · Para Jumble · DSE/SP
(P) Ethics in AI development is no longer philosophical but a practical necessity. (Q) Algorithmic biases can cause real harm to marginalised communities. (R) Developers must build fairness and transparency into AI systems from the outset. (S) Without these safeguards, trust in AI will erode.
A. P-Q-R-S ✓
B. Q-S-P-R
C. R-P-Q-S
D. S-Q-R-P
Answer: A. P-Q-R-S. P establishes the premise. Q gives a specific harm. R proposes the solution. S warns of consequence of inaction.
Q180 · Para Jumble · SE
Identify the sentence that would BEST open a paragraph about digital literacy: (P) Schools must integrate digital literacy. (Q) Understanding technology is as fundamental as reading. (R) Many adults struggle to identify fake news. (S) Digital literacy empowers citizens.
A. P
B. Q ✓
C. R
D. S
Answer: B. Q. Q makes the broad introductory claim. Opening sentences introduce the topic broadly.
Section 8
🟠 Idioms & One-Word Substitution — Q181 to Q200
Idioms, Phrases & One-Word Substitution
These appear especially in DSE and SP roles. Know both literal and figurative meanings.
Q181 · Idioms · SE/DSE
'The new employee was asked to hit the ground running.' This means:
A. Start working outdoors
B. Begin working immediately and energetically ✓
C. Run during work hours
D. Fall down while starting
Answer: B. Begin working immediately and energetically. Hit the ground running = to start something with immediate, energetic effort.
Q182 · Idioms · SE
'She burns the midnight oil before every exam.' This means:
A. She studies late into the night ✓
B. She lights candles while studying
C. She wakes up early to study
D. She sleeps before exams
Answer: A. She studies late into the night. Burn the midnight oil = to work or study late at night.
Q183 · Idioms · SE/DSE
'The project was a blessing in disguise.' This means:
A. The project was hidden from everyone
B. Something that seemed bad turned out to be good ✓
C. The project was dressed up attractively
D. An unexpected project arrived
Answer: B. Something that seemed bad turned out to be good. A blessing in disguise = an apparent misfortune that eventually has good results.
Q184 · Idioms · DSE/SP
'The manager told the team not to beat around the bush.' This means:
A. Avoid unnecessary talk and get to the point ✓
B. Do not go near the garden
C. Do not argue with each other
D. Work without complaining
Answer: A. Avoid unnecessary talk and get to the point. Beat around the bush = to avoid coming to the main point.
Q185 · Phrasal Verb · SE
'The meeting was called off.' CALLED OFF means:
A. Cancelled ✓
B. Postponed
C. Started
D. Extended
Answer: A. Cancelled. Call off = to cancel an event or activity that was planned.
Q186 · One-Word Sub · SE/DSE
A person who can speak two languages fluently:
A. Polyglot
B. Bilingual ✓
C. Multilingual
D. Interpreter
Answer: B. Bilingual. Bilingual = able to speak two languages fluently.
Q187 · One-Word Sub · SE
A government run by the people:
A. Democracy ✓
B. Monarchy
C. Oligarchy
D. Autocracy
Answer: A. Democracy. From Greek: demos (people) + kratos (rule). A system of government by the whole population.
Q188 · One-Word Sub · DSE/SP
The study of the origin and history of words:
A. Phonology
B. Etymology ✓
C. Morphology
D. Lexicology
Answer: B. Etymology. Etymology = the study of the origin and historical development of words.
Q189 · One-Word Sub · SE
A person who eats too much:
A. Glutton ✓
B. Gourmet
C. Herbivore
D. Vegan
Answer: A. Glutton. A glutton is a person who eats excessively.
Q190 · One-Word Sub · SE/DSE
A place where animals are kept for public viewing:
A. Zoo ✓
B. Aquarium
C. Sanctuary
D. Aviary
Answer: A. Zoo. A zoo (zoological garden) is a place where animals are kept for public display.
Q191 · Idioms · SE
'He let the cat out of the bag.' This idiom means:
A. He set a cat free
B. He accidentally revealed a secret ✓
C. He told an animal story
D. He caused confusion
Answer: B. He accidentally revealed a secret. Let the cat out of the bag = to accidentally reveal secret information.
Q192 · One-Word Sub · DSE
Killing of a large group of people, especially those of a particular ethnic group:
A. Homicide
B. Genocide ✓
C. Suicide
D. Fratricide
Answer: B. Genocide. Genocide = deliberate killing of a large group, especially of a particular ethnic group.
Q193 · Phrasal Verb · SE/DSE
'The company decided to call off the strike.' CALL OFF means:
A. Cancel ✓
B. Support
C. Announce
D. Continue
Answer: A. Cancel. To call off = to cancel something that was planned or in progress.
Q194 · Idioms · DSE/SP
'The CEO was walking on thin ice by challenging the board's decision.' This means:
A. He was in a risky or dangerous situation ✓
B. He was walking carefully on ice
C. He was making a bold but safe move
D. He was being extremely cautious
Answer: A. He was in a risky or dangerous situation. Walk on thin ice = to be in a risky situation where danger is just below the surface.
Q195 · One-Word Sub · SE
A person who is against war or use of violence:
A. Pacifist ✓
B. Anarchist
C. Fascist
D. Activist
Answer: A. Pacifist. A pacifist believes war and violence are unjustifiable.
Q196 · Idioms · SE
'She bit the bullet and accepted the pay cut.' This means:
A. She fought against the decision
B. She endured a painful situation bravely ✓
C. She ate something and got sick
D. She quit her job
Answer: B. She endured a painful situation bravely. Bite the bullet = to endure a painful or difficult situation that is inevitable.
Q197 · One-Word Sub · DSE/SP
A person who knows a great deal about many subjects:
A. Polymath ✓
B. Polyglot
C. Pundit
D. Scholar
Answer: A. Polymath. Polymath = a person of wide knowledge across many subjects.
Q198 · Idioms · SE/DSE
'After years of hard work, success finally came. She had turned the corner.' This means:
A. She changed her direction of travel
B. She passed the worst part of a difficult situation ✓
C. She turned her back on success
D. She started a new problem
Answer: B. She passed the worst part of a difficult situation. Turn the corner = to pass the most difficult stage and start to improve.
Q199 · One-Word Sub · SE
The practice of having more than one wife at the same time:
A. Polygamy ✓
B. Bigamy
C. Monogamy
D. Celibacy
Answer: A. Polygamy. Polygamy = the practice of having more than one spouse simultaneously.
Q200 · Idioms · DSE/SP
'The startup's growth was a double-edged sword.' This means:
A. The growth had both advantages and disadvantages ✓
B. The company used two different strategies
C. The startup was growing twice as fast
D. The sword was the company's logo
Answer: A. The growth had both advantages and disadvantages. Double-edged sword = something that has both positive and negative consequences.
FAQ
Frequently Asked Questions
How many verbal ability questions come in Infosys exam? ▼
The Infosys verbal ability section has 20–25 questions in 20–35 minutes. For SE it is 20 questions in 20 minutes. DSE and SP have higher difficulty and may have more questions.
Is there negative marking in Infosys verbal section? ▼
Infosys typically does not impose negative marking. Confirm in your specific exam notification. Attempt every question.
What is the difficulty level for SE vs DSE vs SP? ▼
SE: Easy to Moderate — grammar, basic vocabulary, simple RC. DSE: Moderate to Hard — longer passages, inference questions. SP: Hard — critical reasoning and complex idioms.
How do I improve my Infosys verbal score quickly? ▼
(1) Learn 100 key synonyms/antonyms. (2) Revise grammar rules — subject-verb agreement, tenses, prepositions. (3) For RC, read questions first then the passage. (4) Practice 20 timed questions daily.
Do idioms and one-word substitutions come in all roles? ▼
Idioms are more common in DSE and SP roles. For SE, expect mostly grammar, fill in the blanks, RC and vocabulary. One-word substitution appears across all roles.
Courses
Want Complete Placement Preparation?
Explore all CampusMonk courses — mock tests, recorded programs, and full placement packs.
Cognizant runs three entry-level hiring tracks — GenC (4 LPA), GenC Pro (5.4 LPA), and GenC Next (6.75 LPA). Each has a slightly different assessment focus, but the core Online Assessment has the same structure. Here's the full breakdown so you're not surprised on exam day.
60
Communication Round
Reading, Grammar, Repeat-sentences via mic. Elimination round. Duration: 60 minutes.
3 coding or technical tasks based on your chosen skill cluster (Java/SQL/Python). Duration: 105–120 mins.
1:1
Interview Round
Technical + HR in one interview. GenC Next interviews last ~1 hour and go deep on DSA + DBMS.
💡 No negative marking — attempt every question. The platform is the Safe Assessment Browser (SAB). Tab switching is tracked. Practice on similar timed platforms before your actual exam.
📐
Section 1: Quantitative Aptitude
Q1 – Q20
1
There are 40 students in a class — 14 taking Maths and 29 taking Computer. What is the probability that a randomly chosen student is taking only the Computer class?
▾
A) 40%
B) 55%
C) 65%
D) 70%
✅ Answer: C) 65%
Students taking both = 14 + 29 − 40 = 3. Only Computer = 29 − 3 = 26. Probability = 26/40 = 65%.
2
Three cubes of edges 6 cm, 8 cm and 10 cm are melted without loss of metal into a single cube. What is the edge of the new cube?
If all 6s get inverted and become 9s between 1 and 100 (inclusive), by how much will the sum of all numbers change?
▾
A) 300
B) 330
C) 333
D) None of these
✅ Answer: B) 330
6 at unit place (6, 16, 26… 96) → 10 numbers → increase by 3 each = +30. 6 at tens place (60–69) → 10 numbers → increase by 30 each = +300. Total = 330.
4
Rajesh spent money on 5 pens, 3 notebooks & 9 pencils. Prabhu bought 6 pens, 6 notebooks & 18 pencils and paid 50% more than Rajesh. What % of Rajesh's money was spent on pens?
▾
A) 62.5%
B) 12.5%
C) 75%
D) Cannot be determined
✅ Answer: A) 62.5%
Let Rajesh spend x. Solving the equations: 1 pen = 0.125x. So 5 pens = 0.625x = 62.5%.
5
A person walks at 10 km/h to reach a destination. He walks back the same route at 14 km/h arriving 20 km less. What was the actual distance?
▾
A) 50 km
B) 40 km
C) 60 km
D) 45 km
✅ Answer: A) 50 km
Let x = distance. x/10 = (x+20)/14 → 14x = 10x + 200 → 4x = 200 → x = 50 km.
6
A bus covers 54 km/h without stoppages and 45 km/h with stoppages. For how many minutes per hour does the bus stop?
▾
A) 10
B) 12
C) 20
D) 9
✅ Answer: A) 10 minutes
Distance lost per hour = 54 − 45 = 9 km. Time to cover 9 km at 54 km/h = (9/54) × 60 = 10 minutes.
7
The distance between cities P and Q is 300 km. Train from P starts at 10 AM at 80 km/h; train from Q starts at 11 AM at 40 km/h. At what time do they meet?
▾
A) 12:50 PM
B) 1:00 PM
C) 12:20 PM
D) 12:40 PM
✅ Answer: A) 12:50 PM
By 11 AM, Train P covers 80 km. Remaining = 220 km. Closing speed = 120 km/h. Time = 220/120 = 1 hr 50 min. 11:00 + 1:50 = 12:50 PM.
8
A shopkeeper bought 30 kg rice at ₹40/kg. Sold 40% at ₹50/kg. At what price per kg should he sell the rest to make a 25% overall profit?
▾
A) ₹50
B) ₹40
C) ₹30
D) ₹54
✅ Answer: A) ₹50
Total CP = 30×40 = ₹1200. Required SP = 1200 × 1.25 = ₹1500. SP of first 12 kg = ₹600. Remaining SP needed = ₹900 for 18 kg = ₹50/kg.
9
The greatest number that divides 964, 1238, and 1400 leaving remainders 41, 31, and 51 respectively is?
Average price of 10 books is ₹12. Average price of 8 of those books is ₹11.75. Of the remaining 2 books, one is 60% more than the other. Find the price of each.
▾
A) ₹12 & ₹24
B) ₹24 & ₹18
C) ₹28 & ₹12
D) ₹10 & ₹16
✅ Answer: D) ₹10 & ₹16
Sum of 2 books = 120 − 94 = ₹26. Let cheaper = x, pricier = 1.6x. x + 1.6x = 26 → x = ₹10, other = ₹16.
13
Two trucks face each other 500 cm apart. Each moves forward 100 cm at 50 cm/s, then backward 50 cm at 25 cm/s. How long until they collide?
▾
A) 12 sec
B) 16 sec
C) 13 sec
D) 14 sec
✅ Answer: D) 14 seconds
Each cycle (2s forward + 2s back) each truck nets +50 cm. At 14 sec, each truck has moved 250 cm → total 500 cm → collision.
14
A secret can be told by 2 persons in 5 minutes. Each tells it to 2 more, and so on. How long will it take to reach 768 persons?
▾
A) 500 min
B) 50 min
C) 47.5 min
D) 49 min
✅ Answer: C) 47.5 minutes
Series: 1, 2, 4, 8, …, 512. Up to 512 people = 45 min. Then 256 people tell 256 more → +2.5 min. Total = 47.5 min.
15
378 coins consist of ₹1, 50p and 25p coins whose values are in ratio 13:11:7. How many 50p coins are there?
▾
A) 132
B) 154
C) 176
D) 132
✅ Answer: B) 154
Value ratio 13:11:7 → coin count ratio = 13:22:28 (divide by denomination). Total = 63 parts = 378 → 1 part = 6. 50p coins = 22×6 = 132. (Verify with your actual exam version as ratios vary.)
16
In a group, 6 speak Tamil, 15 speak Hindi, 6 speak Gujarati. 2 speak two languages, 1 speaks all three. How many people are in the group?
▾
A) 21
B) 22
C) 24
D) 23
✅ Answer: D) 23
Only Tamil = 3, Only Hindi = 12, Only Gujarati = 5. Total = 20 + 2 (bilingual) + 1 (trilingual) = 23.
17
A and B can complete a work in 12 days together. B and C in 15 days, A and C in 20 days. How many days will A alone take?
▾
A) 30 days
B) 20 days
C) 24 days
D) 40 days
✅ Answer: A) 30 days
2(A+B+C) = 1/12+1/15+1/20 = 1/5. So A+B+C = 1/10. A alone = 1/10 − 1/15 = 1/30 → 30 days.
18
A train 150 m long passes a telegraph pole in 15 seconds. How long will it take to pass a platform 300 m long?
▾
A) 30 sec
B) 45 sec
C) 40 sec
D) 60 sec
✅ Answer: B) 45 seconds
Speed = 150/15 = 10 m/s. Distance to cross platform = 150+300 = 450 m. Time = 450/10 = 45 seconds.
19
Simple interest on a sum at 5% per annum for 3 years is ₹1200. What is the compound interest on the same sum at the same rate for 2 years?
▾
A) ₹800
B) ₹820
C) ₹840
D) ₹860
✅ Answer: B) ₹820
SI = PRT/100 → 1200 = P×5×3/100 → P = ₹8000. CI for 2 years = 8000×[(1.05)²−1] = 8000×0.1025 = ₹820.
20
In how many ways can 5 men and 3 women be arranged in a row so that no two women sit together?
▾
A) 1440
B) 14400
C) 720
D) 2880
✅ Answer: B) 14400
Arrange 5 men: 5! = 120. Women can sit in 6 gaps (between/outside men): ⁶P₃ = 120. Total = 120 × 120 = 14400.
🧠
Section 2: Logical Reasoning
Q21 – Q40
21
There are 6 cities, every city connected to each other. How many different routes from A to B such that no city is touched more than once?
▾
A) 72
B) 65
C) 60
D) 48
✅ Answer: B) 65
Direct = 1. Via 1 city = 4. Via 2 = 4×3=12. Via 3 = 24. Via 4 = 24. Total = 1+4+12+24+24 = 65.
22
Find the next number in the series: 2, 6, 12, 20, 30, ?
Which number does not belong in the group: 16, 25, 36, 72, 144, 196?
▾
A) 36
B) 72
C) 144
D) 196
✅ Answer: B) 72
All others are perfect squares (4², 5², 6², 12², 14²). 72 is not a perfect square.
38
A is B's sister. C is B's mother. D is C's father. E is D's mother. How is A related to D?
▾
A) Daughter
B) Grand Daughter
C) Great-granddaughter
D) Mother
✅ Answer: B) Grand Daughter
A is B's sister → A and B are children of C. C is D's daughter. So A is D's Grand Daughter.
39
Deductive reasoning game (Geo-Sudo type): In a 3×3 grid, each row and column must contain 1–3 without repetition. If row 1 is [1, _, 3] and column 2 has 3 in row 2, what is row 1 missing number?
▾
A) 2
B) 1
C) 3
D) Cannot determine
✅ Answer: A) 2
Row 1 has 1 and 3. The missing number must be 2 (each number 1–3 appears once per row).
40
What is the angle between the hour and minute hands at 3:15?
▾
A) 0°
B) 7.5°
C) 15°
D) 22.5°
✅ Answer: B) 7.5°
At 3:15, minute hand = 90°. Hour hand = 90 + (15×0.5) = 97.5°. Difference = 7.5°.
📖
Section 3: Verbal Ability
Q41 – Q55
41
Choose the correct sentence: A) She don't know the answer. B) She doesn't knows the answer. C) She doesn't know the answer. D) She not know the answer.
▾
A) Sentence A
B) Sentence B
C) Sentence C
D) Sentence D
✅ Answer: C
"She doesn't know the answer" uses correct subject-verb agreement with third-person singular.
42
Fill in the blank: The committee ______ yet to reach a decision. (has / have)
▾
A) has
B) have
C) are
D) were
✅ Answer: A) has
"Committee" is a collective noun treated as singular in formal English → has.
Verbose means using more words than needed. Wordy is the closest synonym.
45
Spot the error: "The team are playing good in the tournament."
▾
A) team are
B) No error
C) playing good
D) in the
✅ Answer: C) playing good
Should be "playing well" — "well" is the adverb modifying the verb "playing", not the adjective "good".
46
Choose the word closest in meaning to EPHEMERAL:
▾
A) Eternal
B) Transient
C) Permanent
D) Stable
✅ Answer: B) Transient
Ephemeral = lasting for a very short time. Transient has the same meaning.
47
Fill in: Neither the manager nor the employees ______ present for the meeting.
▾
A) was
B) were
C) is
D) has been
✅ Answer: B) were
With "neither…nor", the verb agrees with the subject closer to it (employees = plural) → were.
48
One word substitution: A person who cannot be corrected.
▾
A) Inexplicable
B) Invincible
C) Incorrigible
D) Inexorable
✅ Answer: C) Incorrigible
Incorrigible means a person who cannot be reformed or corrected.
49
Rearrange: TRAMS / SMART / RAMPS — which is NOT an anagram of the others?
▾
A) TRAMS
B) SMART
C) RAMPS
D) All are anagrams
✅ Answer: C) RAMPS
TRAMS and SMART both use T,R,A,M,S. RAMPS uses R,A,M,P,S — different letter (P instead of T) → not an anagram.
50
Choose the correct passive voice: "The manager approved the project."
▾
A) The project was approved by the manager.
B) The project is approved by the manager.
C) The project had been approved the manager.
D) The project approved by the manager.
✅ Answer: A
Simple past active → past passive = "was + past participle by subject" → The project was approved by the manager.
51
Reading comprehension (common type): If the passage says "Technology is a double-edged sword," the author most likely means:
▾
A) Technology is dangerous
B) Technology is beneficial
C) Technology has both benefits and drawbacks
D) Technology is neutral
✅ Answer: C
"Double-edged sword" is an idiom meaning something has both positive and negative effects simultaneously.
52
Which sentence uses the correct tense? "By the time she arrives, we ______ the project."
▾
A) finish
B) finished
C) will have finished
D) were finishing
✅ Answer: C) will have finished
"By the time" with a future reference requires the future perfect tense.
53
Choose the correctly spelled word:
▾
A) Accomodate
B) Acommodate
C) Accommodate
D) Accomadate
✅ Answer: C) Accommodate
Accommodate has double 'c' and double 'm' — a commonly misspelled word in Cognizant verbal tests.
54
Sentence completion: The new software was ______ by the team after weeks of testing. (A) inaugurated (B) demolished (C) deployed (D) confiscated
▾
A) Inaugurated
B) Demolished
C) Deployed
D) Confiscated
✅ Answer: C) Deployed
In a tech context, software is deployed — released for use. This is common Cognizant verbal context.
55
Identify the type of error: "He is one of those employees who works late every night."
▾
A) No error
B) Tense error
C) Subject-verb agreement error
D) Article error
✅ Answer: C
"One of those employees who" requires plural verb → should be "work late every night" because the relative clause refers to "employees" (plural).
💻
Section 4: Technical / CS Fundamentals
Q56 – Q75
56
What is the time complexity of Binary Search?
▾
A) O(n)
B) O(log n)
C) O(n²)
D) O(1)
✅ Answer: B) O(log n)
Binary search halves the search space each iteration → O(log n) time complexity.
57
Which OOP concept is illustrated when a child class inherits methods from a parent class?
▾
A) Encapsulation
B) Polymorphism
C) Inheritance
D) Abstraction
✅ Answer: C) Inheritance
Inheritance allows a class to reuse attributes and methods from another class, forming a parent-child relationship.
58
What does SDLC stand for, and what is its purpose?
▾
A) Software Design Life Cycle — to design software
B) Software Development Life Cycle — systematic process for building software
C) System Deployment Life Cycle — deploying systems
D) Software Debug Life Cycle — fixing bugs
✅ Answer: B
SDLC (Software Development Life Cycle) is the structured process of planning, building, testing, and maintaining software. Phases: Requirement → Design → Implement → Test → Deploy → Maintain.
59
Why is Java considered more secure than C/C++?
▾
A) Java uses pointers
B) Java has no explicit pointer manipulation and runs in JVM sandbox
C) Java is slower
D) Java doesn't use memory
✅ Answer: B
Java eliminates direct memory access via pointers. Programs run in the JVM sandbox, preventing direct OS-level attacks and buffer overflow exploits common in C/C++.
60
What is the output of: print(type([])) in Python?
▾
A) <class 'tuple'>
B) <class 'list'>
C) <class 'dict'>
D) <class 'set'>
✅ Answer: B) <class 'list'>
[] is an empty list literal in Python. type([]) returns <class 'list'>.
61
Which data structure uses LIFO (Last In, First Out) principle?
▾
A) Queue
B) Stack
C) Linked List
D) Tree
✅ Answer: B) Stack
A Stack follows LIFO — the last element added is the first one removed. Like a stack of plates.
62
What is polymorphism in OOP?
▾
A) Hiding data from outside world
B) Inheriting from multiple classes
C) One interface, multiple implementations
D) Storing different data types
✅ Answer: C
Polymorphism means "many forms." The same method name can behave differently depending on the object. Example: method overloading and overriding.
63
What is the difference between a process and a thread?
▾
A) No difference
B) A process has its own memory; threads share process memory
C) A thread is heavier than a process
D) Threads run on different CPUs only
✅ Answer: B
A process = independent program with its own memory. A thread = lightweight unit within a process that shares the same memory space.
64
What does the 'final' keyword mean in Java?
▾
A) The class runs faster
B) Variable/method/class cannot be modified or overridden
C) Method is static
D) It initializes automatically
✅ Answer: B
In Java, final variable = constant, final method = can't be overridden, final class = can't be inherited.
65
What is a primary key in a database?
▾
A) Any column in a table
B) A column (or set of columns) that uniquely identifies each row
C) A foreign key reference
D) An indexed column only
✅ Answer: B
A primary key uniquely identifies each record in a table. It cannot be NULL and must be unique for every row.
66
What is the worst-case time complexity of QuickSort?
▾
A) O(n log n)
B) O(n²)
C) O(n)
D) O(log n)
✅ Answer: B) O(n²)
QuickSort's worst case is O(n²) when the pivot is always the smallest or largest element (e.g., sorted array with bad pivot choice). Average = O(n log n).
67
What is the output of this Java snippet? int x = 5; System.out.println(x++); System.out.println(x);
▾
A) 6 and 6
B) 5 and 6
C) 5 and 5
D) 6 and 5
✅ Answer: B) 5 and 6
x++ is post-increment → prints current value (5) first, then increments. Next print shows 6.
68
Which HTTP method is used to update data on a server (partial update)?
▾
A) GET
B) POST
C) PUT
D) PATCH
✅ Answer: D) PATCH
PATCH is for partial updates. PUT replaces the entire resource. POST creates new. GET retrieves.
69
In an array of size n, what is the time complexity of accessing element at index i?
▾
A) O(1)
B) O(n)
C) O(log n)
D) O(n²)
✅ Answer: A) O(1)
Array elements are stored at contiguous memory locations. Access by index is direct → O(1) constant time.
70
What is encapsulation in OOP?
▾
A) Bundling data and methods together, hiding internal details
B) Creating multiple child classes
C) Writing the same method with different parameters
D) Running code in parallel
✅ Answer: A
Encapsulation wraps data (variables) and methods inside a class and controls access using access modifiers (private, public, protected).
71
What is a deadlock in operating systems?
▾
A) A process running too fast
B) Two or more processes waiting for each other's resources indefinitely
C) An infinite loop in code
D) Memory overflow
✅ Answer: B
A deadlock occurs when processes are stuck in a circular wait — each holds a resource the other needs, so none can proceed.
72
What is the purpose of the 'static' keyword in Java?
▾
A) It makes a variable final
B) It belongs to the class, not to an instance
C) It prevents inheritance
D) It automatically initializes variables
✅ Answer: B
static means the variable or method belongs to the class itself, not to any particular object. All instances share the same static member.
73
What does HTML stand for?
▾
A) Hyper Text Making Language
B) HyperText Markup Language
C) High Transfer Markup Language
D) Hyper Transfer Markup Language
✅ Answer: B) HyperText Markup Language
HTML is the standard language for creating web pages. It uses tags to structure content for display in browsers.
74
What is normalization in database design?
▾
A) Organizing tables to reduce data redundancy and improve integrity
B) Speeding up queries with indexes
C) Encrypting the database
D) Backing up the database
✅ Answer: A
Normalization is the process of organizing database tables to minimize redundancy. Forms: 1NF, 2NF, 3NF, BCNF.
75
What is the difference between == and .equals() in Java?
▾
A) == compares references; .equals() compares actual content/values
B) They are exactly the same
C) == compares values; .equals() compares memory
D) .equals() only works for integers
✅ Answer: A
== checks if two variables point to the same object in memory. .equals() checks if the content of two objects is the same.
⌨️
Section 5: Coding Problems (GenC Next)
Q76 – Q85
76
Write a function to check if a string is a palindrome. What is the most efficient approach?
▾
A) Use nested loops O(n²)
B) Use two-pointer technique O(n)
C) Reverse and compare using recursion O(n log n)
D) Sort and compare O(n log n)
✅ Answer: B) Two-pointer O(n)
Compare characters from both ends moving inward. If any mismatch → not a palindrome.
defis_palindrome(s):
left, right = 0, len(s) - 1while left < right:
if s[left] != s[right]:
returnFalse
left += 1
right -= 1returnTrue
77
There are N suns in a galaxy, each with M planets, each with some moons [galaxy[i][j]]. Find the maximum number of moons in any single solar system.
▾
A) Sum each row, return maximum row sum
B) Find the maximum single cell value
C) Sum all values in the entire grid
D) Count number of columns
✅ Answer: A — Sum rows, find maximum
Each solar system (row) = one sun. Sum all moons per sun, return the highest total.
Find the second largest element in an unsorted array without sorting it. What is the time complexity?
▾
A) O(n log n) — sort then pick
B) O(n) — single pass tracking two variables
C) O(n²) — nested loops
D) O(1) — direct access
✅ Answer: B) O(n)
Track first and second max in one pass.
defsecond_largest(arr):
first = second = float('-inf')
for n in arr:
if n > first:
second = first
first = n
elif n > second and n != first:
second = n
return second
79
Reverse a linked list. Which approach uses O(1) extra space?
▾
A) Store in array then rebuild
B) Iterative three-pointer technique
C) Recursive approach
D) Sort the linked list
✅ Answer: B) Iterative — O(1) space
Use prev, curr, next pointers. No extra memory needed.
What does this code output? x = [1, 2, 3]; y = x; y.append(4); print(x)
▾
A) [1, 2, 3]
B) [1, 2, 3, 4]
C) Error
D) [4, 1, 2, 3]
✅ Answer: B) [1, 2, 3, 4]
y = x does NOT copy the list — both y and x point to the same list object. Modifying y also modifies x. This is Python's reference semantics.
84
Find if a number is prime. What is the most efficient method up to √n?
▾
A) Check divisibility up to n — O(n)
B) Check divisibility up to √n — O(√n)
C) Sieve of Eratosthenes for one number
D) Use modulo of n/2
✅ Answer: B) O(√n)
import math
defis_prime(n):
if n < 2: returnFalsefor i inrange(2, int(math.sqrt(n)) + 1):
if n % i == 0: returnFalsereturnTrue
85
Given a string, find the first non-repeating character. E.g., "swiss" → 'w'
▾
A) Build frequency map then scan in order — O(n)
B) Nested loops to check each char — O(n²)
C) Sort the string — O(n log n)
D) Use recursion
✅ Answer: A) O(n)
from collections import Counter
deffirst_unique(s):
freq = Counter(s)
for ch in s:
if freq[ch] == 1:
return ch
returnNone
🗄️
Section 6: SQL & DBMS
Q86 – Q93
86
What is the difference between WHERE and HAVING in SQL?
▾
A) No difference
B) WHERE filters rows before grouping; HAVING filters groups after GROUP BY
C) HAVING is faster than WHERE
D) WHERE works only on strings
✅ Answer: B
WHERE filters individual rows before any grouping. HAVING filters after GROUP BY — used with aggregate functions like COUNT, SUM, AVG.
87
Write a query to find employees who earn more than the average salary.
▾
A) SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
B) SELECT * FROM employees HAVING salary > AVG(salary);
C) SELECT AVG(salary) FROM employees WHERE salary > 0;
D) SELECT * FROM employees ORDER BY salary DESC;
✅ Answer: A
SELECT * FROM employees
WHERE salary > (SELECTAVG(salary) FROM employees);
88
What is the difference between INNER JOIN and LEFT JOIN?
▾
A) INNER JOIN returns only matching rows; LEFT JOIN returns all rows from left table even without a match
B) They are the same
C) LEFT JOIN is faster
D) INNER JOIN returns all rows from both tables
✅ Answer: A
INNER JOIN = only rows where condition matches in BOTH tables. LEFT JOIN = all rows from left table + matched rows from right (NULLs for no match).
89
What is a foreign key?
▾
A) Key from another database
B) A column that references the primary key of another table
C) An alternate primary key
D) A key that allows NULL values only
✅ Answer: B
A foreign key establishes a relationship between two tables. It references the primary key of another table to maintain referential integrity.
90
Write a query to find the second highest salary from an Employee table.
▾
A) SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
B) SELECT salary FROM employees ORDER BY salary DESC LIMIT 1;
C) SELECT MIN(salary) FROM employees;
D) SELECT salary FROM employees GROUP BY salary;
✅ Answer: A
SELECTMAX(salary) FROM employees
WHERE salary < (SELECTMAX(salary) FROM employees);
91
What does the GROUP BY clause do in SQL?
▾
A) Sorts the results
B) Groups rows with the same values into summary rows for aggregate functions
C) Filters duplicate rows
D) Joins multiple tables
✅ Answer: B
GROUP BY groups rows sharing a value so aggregate functions (COUNT, SUM, AVG) can be applied per group. Example: count employees per department.
92
What is the difference between DELETE, DROP, and TRUNCATE in SQL?
▾
A) DELETE removes rows (can rollback); TRUNCATE removes all rows (faster, no rollback); DROP removes the entire table
B) They are all the same
C) DROP is reversible, DELETE is not
D) TRUNCATE removes the table structure
✅ Answer: A
DELETE: removes specific rows, logged, can be rolled back. TRUNCATE: removes all rows instantly, not easily rolled back. DROP: removes the entire table including its structure.
93
What is an index in a database and why is it used?
▾
A) It sorts data alphabetically
B) It speeds up data retrieval by creating a lookup structure
C) It encrypts the table
D) It is used to join tables
✅ Answer: B
A database index is like a book's table of contents — it allows the database engine to find rows quickly without scanning the entire table. It speeds up SELECT queries but slightly slows INSERT/UPDATE.
🤝
Section 7: HR Interview Questions
Q94 – Q100
94
Tell me about yourself. What should you focus on?
▾
A) Your entire life story
B) Your family background
C) Education → Skills → Projects → Why Cognizant
D) Your hobbies only
✅ Best Approach
Structure: Name + degree + college → key technical skills → most relevant project → why you want to work at Cognizant. Keep it to 90 seconds. End with enthusiasm about the role.
95
Why do you want to work at Cognizant?
▾
A) "Because it pays well"
B) Mention Cognizant's work culture, learning opportunities, digital transformation projects
C) "I applied everywhere"
D) "It's close to my home"
✅ Best Approach
Talk about Cognizant's focus on digital transformation, cloud, AI, and their global presence. Mention how their GenC/GenC Next training programs align with your goal of building a strong technical foundation early in your career.
96
What is your greatest weakness?
▾
A) "I have no weaknesses"
B) "I work too hard"
C) Name a real weakness + what you're doing to improve it
D) "I hate working in teams"
✅ Best Approach
Be honest but strategic. Example: "I sometimes struggle with public speaking, but I've been joining group discussions and tech meetups to practice. I've noticed a visible improvement in the last few months." Shows self-awareness + initiative.
97
Where do you see yourself in 5 years?
▾
A) "Running my own company"
B) "In your position"
C) "Growing into a technical lead role within Cognizant, specializing in cloud/AI"
D) "Retired"
✅ Best Approach
Show ambition but tie it to Cognizant's growth. Example: "I want to develop expertise in cloud solutions and eventually contribute as a solution architect. I see Cognizant as the perfect place to grow because of your training programs and global projects."
98
Describe a situation where you worked in a team to solve a problem. (STAR method)
▾
A) Make up a story
B) Say you always work alone
C) Use Situation → Task → Action → Result format with a real example
D) Keep it vague
✅ Best Approach
Use the STAR method: Situation (project context) → Task (your role) → Action (what you did specifically) → Result (measurable outcome). Example: College project where your team was stuck on a bug and you led the debugging session, reducing submission delay from 2 days to 6 hours.
99
Are you comfortable relocating?
▾
A) "Yes, I am open to relocation" (if true)
B) Refuse without explanation
C) Negotiate aggressively
D) Ask them to confirm your city first
✅ Best Approach
Cognizant often posts across multiple cities. If you're open to relocation, say so clearly and positively: "Yes, I'm open to working wherever the opportunity is. I believe exposure to different work environments will help me grow faster."
100
Do you have any questions for us? (End of interview)
▾
A) "No, I'm good"
B) Ask about salary immediately
C) Ask about the team, training program, or a recent Cognizant project
D) Ask when you'll get the offer letter
✅ Best Approach
Always have 1–2 thoughtful questions ready. Examples: "What does the typical learning curve look like for a GenC associate in the first 6 months?" or "What technologies does the team I'd be joining primarily work with?" This shows genuine interest and preparation.
🎯 Ready to Crack the Cognizant OA?
You've just gone through 100 real questions. Now it's time to practice under timed conditions. Accuracy + Speed = Selection.
Exact questions asked in TCS Digital and Prime role interviews, actual student experiences, and everything you need to walk in confident.
CampusMonkDigital & Prime Roles10 min read
"Sir, what happens in the TCS interview?" — This is the most common question every student asks after clearing TCS NQT. This blog gives you the real answers — from students who actually sat in the interview room in 2026.
You cleared the TCS NQT. Now comes the interview.
This is where most students get confused. They don't know what to expect. They prepare the wrong things. They get nervous for no reason.
The truth is — the TCS interview is very structured. Once you know what they ask, it becomes much less scary.
This blog covers everything — TCS HR Round questions, TCS Technical Round topics, and TCS Managerial Round — with real questions from actual 2026 TCS interviews for Digital and Prime roles.
Interview Structure
TCS Interview Structure 2026
Before we go into each round, understand this simple structure. TCS campus interviews have 3 rounds — all on the same day:
👩💼
Round 1
HR Round
Personality & fit check
💻
Round 2
Technical Round
Projects, SQL, coding
🤝
Round 3
Managerial Round
Attitude & flexibility
The good news? Most students who cleared TCS NQT also clear the interview — because TCS is looking for attitude and willingness to learn, not perfection.
HR Round
Round 1 — TCS HR Round Questions (with Answers)
The HR round is a simple 15–20 minute conversation. They are checking if you are genuine, confident, and a good fit for TCS culture.
Here are the most common TCS HR interview questions with tips on how to answer each:
HR Round Questions Asked in TCS 2026
Tell me about yourself — Prepare a 90-second answer: name, college, branch, key skills, one project, and why TCS.
Why did you choose this college? — Be honest. Keep it short and positive.
What do you know about TCS? — Mention TCS's size (largest IT company in India), its digital transformation work, global presence in 50+ countries, and its focus on fresher hiring.
Why do you want to join TCS? — Don't say "big company." Say: learning opportunities, global exposure, strong training program for freshers.
What are your strengths and weaknesses? — Give a real weakness. Always say how you are working to improve it.
What are your hobbies and interests? — Be genuine. If you say "coding," be ready to talk about it.
Why should we hire you? — Combine your skills, your attitude to learn, and your enthusiasm. Keep it to 60 seconds.
Pro Tip for HR Round: The biggest mistake students make is memorising answers word by word. The interviewer can tell. Instead, understand what each answer should communicate — then speak naturally. Practise out loud, not on paper.
Technical Round
Round 2 — TCS Technical Round Questions
This is the round students fear most. But here is the truth — TCS technical interviews mostly stay close to your resume and projects. They rarely go into deep DSA or system design for freshers.
Technical Topics Asked in TCS Digital & Prime 2026
Your Project Deep Dive — What did you build? What technology? How does the backend work? What problems did you face?
Networking Questions — API Gateway, IP Address, how a browser connects to a server (DNS → TCP → HTTP)
Spring Boot Concepts — For Java students: annotations, REST API, auto-configuration basics
SQL Queries — Joins, Subquery, Indexing, EXISTS, NOT EXISTS, IN, NOT IN, GROUP BY, HAVING
SQL Set Operations — Union, Union All, Intersect, Minus — know the differences
Basic Coding Problem — "Write a code to return the second maximum element"
Cloud Computing Basics — What is cloud? Public vs Private vs Hybrid. Basic understanding is enough.
SQL Topics You Must Revise Before TCS Technical Interview
SQL is asked in almost every TCS technical interview. These are the exact topics that come up most frequently:
SQL Topic
What to Know
Difficulty
Joins
INNER, LEFT, RIGHT, FULL OUTER — know with examples
Must Know
Subquery
Nested SELECT, correlated subquery
Must Know
Indexing
Why index speeds up queries, clustered vs non-clustered
Must Know
EXISTS / NOT EXISTS
Difference from IN / NOT IN, when to use which
Important
GROUP BY / HAVING
Difference between WHERE and HAVING
Must Know
Union vs Union All
Union removes duplicates, Union All keeps them
Important
Intersect / Minus
Common rows vs difference between result sets
Good to Know
Managerial Round
Round 3 — TCS Managerial Round Questions
Managerial Questions in TCS 2026
The most relaxed round. They are checking attitude, flexibility, and if you will fit into TCS work culture.
How many family members do you have?
Are you vegetarian or non-vegetarian? — No right answer. Just be honest.
Any location preferences? — "No preference" is the safest and best answer.
What are your strengths and weaknesses?
What are your hobbies and interests?
Why should we hire you? — Your final chance to make an impression.
The Managerial round rarely eliminates candidates. Think of it as a final check. Be relaxed, be natural, be honest.
Real Experience
Real TCS Interview Experience — A Student's Story
One of our CampusMonk students shared exactly what happened in their TCS Technical Round in 2026. This is one of the most valuable things you can read before your interview.
Technical Round — Actual Questions Asked (Student's Own Words)
1Interviewer asked: "Do you know about Cloud Computing?" — Student replied: "I know the basics but not in-depth." Interviewer said "OK" and moved on. Don't lie. Honesty works.
2Asked Networking questions — API Gateway, IP address, how browser connects with the server.
3Spring Boot related questions asked (student had Java in their resume).
4Asked to connect project with backend code. Student said MySQL not implemented yet — interviewer said "OK" and continued. Partial knowledge is fine. Don't freeze.
5"Write a code to return the second maximum element." Student wrote it correctly with just one small semicolon syntax error — still cleared the round.
6Personal question: "Why not defence exams since your father is in the army?" — Student said: "My passion is in IT." Short, honest, confident answer.
What this experience teaches us: TCS interviewers are not trying to fail you. They want to see how you think under pressure, how honest you are, and whether you can communicate clearly. You don't need to know everything — just know what you've put on your resume, be genuine, and stay calm.
Free Video
Watch This Free Video Before Your TCS Interview
This free YouTube session covers real TCS interview questions from Digital and Prime roles in 2026 — HR Round, Technical Round, and Managerial Round in one complete video.
CampusMonk — Free YouTube Session
TCS Interview Questions | Prime & Digital Actual Experience + Real Questions 2026
Real questions. Real answers. Real student experiences. HR + Technical + Managerial Round — all in one video. Completely free.
These are not generic tips. These come from students who sat in real TCS interviews and the questions they got wrong — or right.
Tip 01
Be honest about what you don't know. Saying "I'm not sure, but I'd approach it this way" is far better than guessing wrong.
Tip 02
Know your project inside out. Every technology on your resume is a potential question. If you put Java, be ready to write Java code.
Tip 03
Practise speaking out loud. Preparing silently is not enough. Record yourself answering, then listen back critically.
Tip 04
Dress formally and arrive 15 minutes early. First impressions shape the entire interview, especially in HR round.
Tip 05
Show your thinking, not just your answer. If stuck on coding, say what you're thinking. Interviewers value problem-solving approach.
Tip 06
Revise SQL the night before. Joins, Subqueries, Indexing — these come up in almost every TCS technical interview.
Tip 07
Prepare 2 questions to ask the interviewer. "What does a typical day look like for a fresher?" shows genuine interest.
Tip 08
Stay calm in Managerial round. It's mostly a conversation. Relax. Be yourself. There are no wrong answers about your family or food preferences.
FAQ
Frequently Asked Questions — TCS Interview 2026
These are the questions that students ask most about the TCS interview process. The FAQ schema on this page means Google may show these answers directly in search results.
How many rounds are there in TCS interview? ▼
TCS interview has 3 rounds — HR Round, Technical Round, and Managerial Round. All three rounds typically happen on the same day. Most students who clear TCS NQT also clear the interview.
What questions are asked in TCS HR Round? ▼
Common TCS HR round questions include: Tell me about yourself, Why do you want to join TCS, What do you know about TCS, What are your strengths and weaknesses, Why should we hire you, and questions about hobbies and interests.
What SQL topics come in TCS Technical Interview? ▼
TCS technical interviews commonly ask about: Joins (Inner, Left, Right, Full), Subqueries, Indexing, EXISTS and NOT EXISTS, IN and NOT IN, GROUP BY with HAVING, Union vs Union All, Intersect, and Minus. Revise all these before your interview.
Is TCS Managerial Round eliminatory? ▼
The TCS Managerial Round rarely eliminates candidates. It checks your attitude, flexibility, and personality. Questions include location preference, family details, and hobbies. Just be natural and honest — there are no wrong answers here.
What is the difference between TCS Digital and TCS Prime interview? ▼
Both have a similar 3-round interview structure. TCS Digital (higher package ~7 LPA) may have slightly more technical depth — especially in advanced SQL, cloud basics, and project explanation. TCS Prime is the standard fresher role (~3.36 LPA) with more general technical questions.
What coding questions come in TCS technical interview? ▼
TCS typically asks 1 basic coding question in the technical round. Common ones: find the second maximum element, reverse a string, check palindrome, print Fibonacci series, or factorial. These are medium-easy problems. Focus on logic and clean code — not advanced DSA.
Final Words
The TCS interview is not as scary as it looks from outside.
They are not trying to fail you. TCS is looking for students who are genuine, curious, and willing to learn.
You don't need to know everything. You need to know your basics well, explain your project clearly, and communicate honestly.
Know your project. Revise SQL. Practise your self-introduction. And walk in with a smile.
TCS Interview Questions 2026: Real HR, Technical and Managerial Round Questions
If you have cleared TCS NQT, the next big step is the interview. Most students feel confused at this stage because they do not know what really happens in the HR, technical, and managerial rounds. The good part is that the TCS interview pattern is quite structured, and once you know what is usually asked, your preparation becomes much easier. This draft focuses on the common 3-round structure, real questions, SQL topics, and actual student experience for TCS Digital and Prime roles.
In this blog, you will find the TCS interview structure for 2026, the most asked HR round questions, technical round topics, managerial round expectations, common SQL areas, basic coding questions, and practical preparation tips. The source draft also positions this as a real-experience based guide for TCS Digital and Prime interviews.
TCS Interview Structure 2026
According to the draft, the TCS interview process is presented as a 3-round structure that usually includes the HR round, technical round, and managerial round. The blog draft also states that these rounds commonly happen on the same day.
The three rounds are:
1. HR Round
This round checks your communication, confidence, and overall personality fit.
2. Technical Round
This round focuses on your resume, projects, SQL concepts, and one or two basic technical questions.
3. Managerial Round
This round is mainly about attitude, flexibility, and whether you are a good fit for the work culture.
One important takeaway from the draft is that the TCS interview is not designed to scare students. It is shown as a structured process where clarity, honesty, and basic preparation matter more than trying to sound perfect.
TCS HR Round Questions 2026
The draft describes the HR round as a simple conversation where the interviewer checks whether you are genuine, confident, and able to communicate clearly. It highlights these as the most common HR round questions.
Common TCS HR Interview Questions
Tell me about yourself
Why did you choose this college?
What do you know about TCS?
Why do you want to join TCS?
What are your strengths and weaknesses?
What are your hobbies and interests?
Why should we hire you?
How to answer HR questions well
For “Tell me about yourself,” keep your answer short and structured. Mention your name, college, branch, skills, one project, and why you want to join TCS. The draft also recommends not memorizing answers word for word and instead speaking naturally.
For “Why TCS?”, avoid generic lines like “because it is a big company.” A better answer is to talk about learning opportunities, fresher training, and growth exposure, which the source draft specifically emphasizes.
TCS Technical Interview Questions 2026
The technical round is usually the most feared part, but the draft makes one thing very clear: TCS technical interviews mostly stay close to your resume and your project work. It specifically says the interview generally does not go very deep into advanced DSA or system design for freshers.
Topics asked in TCS technical interview
The uploaded draft lists these commonly asked technical areas:
Project deep dive
Networking questions
Spring Boot basics for Java students
SQL queries
SQL set operations
One basic coding question
Cloud computing basics
1. Project-based questions
Your project is one of the most important parts of the technical round. You should be ready to explain:
What the project does
Which technologies you used
How the backend works
What challenges you faced
What features are incomplete or still pending
The draft repeatedly suggests that interviewers often ask questions from whatever is written in your resume, especially project tools and technologies.
2. SQL questions
The draft highlights SQL as one of the most important topics in the TCS technical interview and says it appears in almost every technical round. It specifically names joins, subqueries, indexing, EXISTS, NOT EXISTS, IN, NOT IN, GROUP BY, HAVING, UNION, UNION ALL, INTERSECT, and MINUS.
3. Networking questions
The draft mentions that students may be asked about:
API Gateway
IP address
How a browser connects to a server
These questions are meant to test fundamentals, not advanced theory.
4. Basic coding questions
The sample coding question explicitly mentioned in the source is: Write a code to return the second maximum element.
This suggests that coding questions are usually logic-based and not extremely difficult.
SQL Topics You Must Revise Before TCS Interview
If you are preparing for the TCS technical round, SQL should be high priority. The source draft provides a clear list of SQL topics to revise.
Important SQL topics
INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN
Subqueries and correlated subqueries
Indexing basics
EXISTS and NOT EXISTS
IN and NOT IN
GROUP BY and HAVING
UNION vs UNION ALL
INTERSECT
MINUS
A strong strategy is to not just memorize definitions. Practise simple examples for each one so you can explain them in the interview confidently.
TCS Managerial Round Questions 2026
The managerial round is described in the draft as the most relaxed round. It is mainly used to check your attitude, flexibility, and personality.
Common managerial round questions
How many family members do you have?
Are you vegetarian or non-vegetarian?
Do you have any location preferences?
What are your strengths and weaknesses?
What are your hobbies and interests?
Why should we hire you?
The draft suggests that “No preference” is often the safest answer when asked about location preference. It also notes that this round rarely eliminates candidates, so the best approach is to stay calm, honest, and natural.
Real TCS Interview Experience 2026
One of the strongest parts of the uploaded draft is the real student experience section. It shares actual examples from a TCS technical interview in 2026 and shows the kind of questions that were asked.
Here are the key takeaways from that experience:
The interviewer asked whether the student knew cloud computing. The student answered honestly and said they only knew the basics. The interviewer accepted that and moved on. This shows that honesty works better than pretending to know everything.
The student was asked networking questions such as API Gateway, IP address, and how a browser connects to a server.
The interviewer also asked Spring Boot questions because Java was mentioned in the resume. This again shows that resume-based preparation matters a lot.
The student was asked to connect the project explanation with backend code. Even when the student said that MySQL was not yet implemented, the interviewer still continued the discussion normally.
A coding question on the second maximum element was asked, and even with a small syntax mistake, the student still cleared the round.
This section clearly supports the draft’s main message: TCS interviewers want to see how you think, how honestly you respond, and how well you communicate under pressure.
8 Tips to Clear TCS Interview
The source draft includes a tip section that can be simplified into these practical points.
1. Be honest
If you do not know something, say it clearly. Honest answers create a better impression than fake confidence.
2. Know your project deeply
Be ready for any question based on the tools, frameworks, and features written in your resume.
3. Practise speaking
Do not only prepare answers in your head. Speak them out loud.
4. Dress formally
First impressions still matter, especially in the HR round.
5. Explain your thought process
When solving coding problems, talk through your logic.
6. Revise SQL
This is one of the most repeated themes in the source draft.
7. Prepare one or two questions for the interviewer
This shows genuine interest.
8. Stay calm in the managerial round
Treat it like a conversation, not an interrogation.
Frequently Asked Questions
How many rounds are there in TCS interview?
The uploaded draft describes the TCS interview as a 3-round process: HR, Technical, and Managerial.
What questions are asked in TCS HR round?
The draft lists questions such as Tell me about yourself, Why TCS, What do you know about TCS, strengths and weaknesses, hobbies, and Why should we hire you.
What SQL topics are asked in TCS technical interview?
The source includes joins, subqueries, indexing, EXISTS, NOT EXISTS, IN, NOT IN, GROUP BY, HAVING, UNION, UNION ALL, INTERSECT, and MINUS.
Is TCS managerial round difficult?
The draft describes it as the most relaxed round and says it rarely eliminates candidates.
What coding questions are asked in TCS technical interview?
The example specifically mentioned in the draft is finding the second maximum element.
Final Words
The TCS interview is not as difficult as students imagine. It is a structured process that rewards honest communication, project clarity, SQL basics, and calm behaviour more than perfect knowledge. That message is repeated across the interview pattern, real student experience, and tips sections.
If you prepare your self-introduction, revise SQL, understand your projects well, and stay honest during the interview, you will already be ahead of many students.
TCS NQT — 100 ACTUAL INTERVIEW QUESTIONS WITH ANSWERS
Q1. ⭐ Write a SQL query to find the second highest salary from the Employee table.
Answer:
-- Method 1: Subquery
SELECT MAX(salary) AS SecondHighest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- Method 2: DENSE_RANK (handles duplicates correctly)
SELECT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) t WHERE rnk = 2;
-- Method 3: LIMIT OFFSET (MySQL)
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
Q2. ⭐ What is the difference between WHERE and HAVING clause?
Answer:
WHERE
HAVING
Used with
Individual rows
Groups (after GROUP BY)
Filters
Before aggregation
After aggregation
Can use aggregate functions
No
Yes
Example
WHERE salary > 50000
HAVING AVG(salary) > 50000
-- WHERE filters rows before grouping
SELECT dept, AVG(salary) FROM employees
WHERE salary > 20000
GROUP BY dept
HAVING AVG(salary) > 50000;
-- HAVING filters after grouping
Q3. ⭐ What are the different types of JOINs? Explain with example.
Answer:
INNER JOIN — Only matching rows from both tables.
SELECT e.name, d.dept_name
FROM employees e INNER JOIN departments d ON e.dept_id = d.id;
LEFT JOIN — All rows from left table + matching from right (NULL if no match).
SELECT e.name, d.dept_name
FROM employees e LEFT JOIN departments d ON e.dept_id = d.id;
RIGHT JOIN — All rows from right table + matching from left.
FULL OUTER JOIN — All rows from both tables (NULL where no match).
SELF JOIN — Table joined with itself.
SELECT a.name AS employee, b.name AS manager
FROM employees a JOIN employees b ON a.manager_id = b.id;
CROSS JOIN — Cartesian product of both tables.
Q4. ⭐ What is the difference between DELETE, TRUNCATE, and DROP?
Answer:
DELETE
TRUNCATE
DROP
Type
DML
DDL
DDL
Rollback
Yes
No
No
WHERE clause
Yes
No
No
Deletes structure
No
No
Yes
Triggers fire
Yes
No
No
Speed
Slow (row by row)
Fast
Fast
DELETE FROM employees WHERE id = 5; -- removes specific row
TRUNCATE TABLE employees; -- removes all rows, keeps structure
DROP TABLE employees; -- removes table completely
Q5. ⭐ What is the difference between DDL, DML, DCL, and TCL?
Q6. ⭐ Write a query to find all employees whose name starts with ‘A’.
Answer:
SELECT * FROM employees
WHERE name LIKE 'A%';
-- Other LIKE patterns:
-- LIKE '%A' → ends with A
-- LIKE '%A%' → contains A anywhere
-- LIKE '_A%' → second character is A
Q7. ⭐ What is a GROUP BY clause? Write a query to find department-wise employee count.
Answer:GROUP BY groups rows with the same values into summary rows.
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
ORDER BY employee_count DESC;
-- With HAVING to filter groups:
SELECT department, COUNT(*) AS cnt
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
Q8. ⭐ What is a subquery? What are its types?
Answer: A subquery is a query nested inside another query.
Types:
Single-row subquery — returns one row: WHERE salary = (SELECT MAX(salary) FROM employees)
Multi-row subquery — returns multiple rows: WHERE dept_id IN (SELECT id FROM departments WHERE location = 'Mumbai')
Correlated subquery — references outer query: executes once per outer row
Scalar subquery — returns single value, used in SELECT list
-- Correlated subquery example:
SELECT name FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id);
Q9. ⭐ What is an INDEX in SQL? What are its advantages and disadvantages?
Answer: An index is a data structure (usually B-Tree) that speeds up data retrieval from a table.
CREATE INDEX idx_salary ON employees(salary);
CREATE UNIQUE INDEX idx_email ON employees(email);
Advantages:
Faster SELECT and WHERE query performance
Faster sorting and ordering
Disadvantages:
Slows down INSERT, UPDATE, DELETE (index must be updated)
Consumes additional disk space
When NOT to use: Small tables, columns with many NULL values, columns rarely used in WHERE clauses.
Q10. ⭐ What are aggregate functions in SQL? Give examples.
Answer: Aggregate functions perform calculations on a set of values and return a single value.
Function
Description
Example
COUNT()
Count rows
SELECT COUNT(*) FROM employees
SUM()
Total sum
SELECT SUM(salary) FROM employees
AVG()
Average
SELECT AVG(salary) FROM employees
MAX()
Maximum
SELECT MAX(salary) FROM employees
MIN()
Minimum
SELECT MIN(salary) FROM employees
SELECT dept, COUNT(*) AS headcount, AVG(salary) AS avg_sal,
MAX(salary) AS max_sal, MIN(salary) AS min_sal
FROM employees
GROUP BY dept;
Q11. ⭐ What is the difference between UNION and UNION ALL?
Answer:
UNION
UNION ALL
Duplicates
Removes duplicates
Keeps all duplicates
Performance
Slower (sorts to remove duplicates)
Faster
Use when
Need unique results
Need all records including duplicates
SELECT name FROM employees_india
UNION
SELECT name FROM employees_usa; -- unique names only
SELECT name FROM employees_india
UNION ALL
SELECT name FROM employees_usa; -- all names including duplicates
Q12. ⭐ Write a SQL query to find employees who earn more than the average salary.
Answer:
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC;
-- With department-wise average:
SELECT e.name, e.salary, e.department
FROM employees e
WHERE e.salary > (
SELECT AVG(salary) FROM employees
WHERE department = e.department
)
ORDER BY e.department, e.salary DESC;
🟠 OOPs — Q13 to Q24
Q13. ⭐ What are the four pillars of OOPs? Explain each with a real-life example.
Answer:
Encapsulation — Wrapping data and methods into a single unit (class) and restricting direct access to data. Real-life: A medicine capsule hides its contents. You take it without knowing what’s inside.
class BankAccount {
private double balance; // hidden data
public double getBalance() { return balance; } // controlled access
public void deposit(double amt) { if(amt > 0) balance += amt; }
}
Abstraction — Hiding implementation details, showing only what is necessary. Real-life: You drive a car without knowing how the engine works internally.
abstract class Shape {
abstract double area(); // what — not how
}
class Circle extends Shape {
double r;
double area() { return 3.14 * r * r; }
}
Inheritance — A child class acquires properties and behaviours of a parent class. Real-life: A child inherits traits (eye colour, height) from parents.
class Animal { void eat() { System.out.println("eating"); } }
class Dog extends Animal { void bark() { System.out.println("Woof"); } }
Polymorphism — Same method name behaves differently based on context. Real-life: A person acts differently as a parent, employee, and friend.
Compile-time (Overloading): same method name, different parameters
Run-time (Overriding): child class redefines parent method
Q14. ⭐ What is the difference between an abstract class and an interface?
Answer:
Abstract Class
Interface
Methods
Abstract + Concrete
Only abstract (Java 7); default/static (Java 8+)
Variables
Any type
public static final only
Constructor
Yes
No
Multiple inheritance
No (single)
Yes (multiple)
Access modifier
Any
public by default
Use when
Base class with shared logic
Define a contract/capability
abstract class Vehicle {
String brand; // instance variable
abstract void start(); // must override
void fuel() { System.out.println("needs fuel"); } // concrete
}
interface Electric { void charge(); }
class Tesla extends Vehicle implements Electric {
void start() { System.out.println("silent start"); }
public void charge() { System.out.println("charging"); }
}
Q15. ⭐ What is the difference between method overloading and method overriding?
Answer:
Overloading
Overriding
Also called
Compile-time polymorphism
Run-time polymorphism
Where
Same class
Parent–child class
Method signature
Different parameters
Same signature
Return type
Can differ
Must be same or covariant
@Override annotation
No
Yes (recommended)
Static methods
Can be overloaded
Cannot be overridden
// Overloading — same class
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // different params
}
// Overriding — child class
class Animal { void sound() { System.out.println("..."); } }
class Cat extends Animal {
@Override
void sound() { System.out.println("Meow"); } // same signature
}
Q16. ⭐ What is a constructor? What are its types? Can a constructor be private?
Answer: A constructor is a special method called when an object is created. It has the same name as the class and no return type.
Types:
Default constructor — No parameters; provided by Java if no constructor defined
Parameterised constructor — Takes arguments to initialise fields
Copy constructor — Creates object by copying another object (C++ has it natively)
Can a constructor be private? Yes — used in Singleton Pattern to prevent external instantiation.
class Singleton {
private static Singleton instance;
private Singleton() { } // private constructor
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
Q17. ⭐ What is the difference between this and super keyword?
Q18. ⭐ What is a virtual function? What is a pure virtual function?
Answer:Virtual function — A function in base class declared with virtual keyword. Enables run-time polymorphism — the correct overridden version is called through a base class pointer/reference.
Pure virtual function — A virtual function with no body (= 0). Makes the class abstract — cannot be instantiated. Any derived class MUST override it.
class Shape {
public:
virtual void draw() { cout << "drawing shape"; } // virtual
virtual double area() = 0; // pure virtual
};
class Circle : public Shape {
public:
void draw() override { cout << "drawing circle"; }
double area() override { return 3.14 * r * r; }
private:
double r = 5;
};
// Shape s; // ERROR — cannot instantiate abstract class
Circle c; // OK — all pure virtual functions overridden
Q19. ⭐ What is a destructor? When is it called?
Answer: A destructor is a special method that is automatically called when an object goes out of scope or is explicitly deleted. It cleans up resources (memory, file handles, connections) allocated by the object.
class FileHandler {
FILE* fp;
public:
FileHandler(const char* name) { fp = fopen(name, "r"); }
~FileHandler() { // destructor
if (fp) fclose(fp); // auto cleanup
cout << "File closed";
}
};
// Destructor called automatically when object scope ends
Key points:
Name = ~ClassName()
No parameters, no return type
Called in reverse order of construction
In Java, finalize() plays a similar role (but garbage collector handles most cleanup)
Q20. ⭐ What is multiple inheritance? Why doesn’t Java support it?
Answer:Multiple inheritance — A class inheriting from more than one parent class.
Java doesn’t support multiple inheritance for classes because of the Diamond Problem:
A
/ \
B C
\ /
D ← Which version of A's method should D use?
If B and C both override a method from A, and D inherits from both B and C, it’s ambiguous which version D should call.
Java’s solution: Java allows multiple inheritance through interfaces (since interfaces had no implementation in Java 7; Java 8 default methods have explicit resolution rules).
interface B { default void show() { System.out.println("B"); } }
interface C { default void show() { System.out.println("C"); } }
class D implements B, C {
public void show() { B.super.show(); } // explicitly resolve conflict
}
Q21. ⭐ What is the difference between composition and inheritance? When to use which?
Answer:
Inheritance
Composition
Relationship
“IS-A”
“HAS-A”
Coupling
Tight
Loose
Flexibility
Less
More
Example
Dog IS-A Animal
Car HAS-A Engine
// Inheritance (IS-A)
class Dog extends Animal { }
// Composition (HAS-A) — preferred over inheritance
class Car {
private Engine engine; // Car HAS-A Engine
private Wheels wheels;
Car() { engine = new Engine(); wheels = new Wheels(); }
}
Rule: Prefer composition over inheritance (GoF principle). Use inheritance only when there’s a genuine IS-A relationship that won’t change.
Q22. ⭐ What is the concept of encapsulation? How is it achieved in Java?
Answer: Encapsulation = bundling data (fields) and methods that operate on data into a single unit (class), and restricting direct access to the internal state.
Achieved through:
Making fields private
Providing public getter/setter methods with validation logic
class Employee {
private String name;
private double salary;
public String getName() { return name; }
public void setName(String name) {
if (name != null && !name.isEmpty())
this.name = name;
}
public double getSalary() { return salary; }
public void setSalary(double salary) {
if (salary > 0) this.salary = salary; // validation
}
}
Benefits: Data hiding, controlled access, easier maintenance, increased flexibility.
Q23. ⭐ Is C++ a purely object-oriented language? Is Java?
Answer:C++: NOT purely object-oriented. Reasons:
You can write functions outside classes
Has primitive data types (int, char, float) which are not objects
main() exists outside any class
Supports procedural programming
Java: NOT purely object-oriented either (despite common belief). Reasons:
Has primitive data types (int, long, double, boolean) which are not objects
Static methods can be called without creating objects
However, Java is MORE object-oriented than C++
Purely OOP languages: Smalltalk, Ruby — where everything including numbers are objects.
Q24. ⭐ What is the difference between a class and an object?
Answer:
Class
Object
Definition
Blueprint/template
Instance of a class
Memory
No memory (blueprint)
Allocated in heap
Creation
Written by programmer
Created using new
Analogy
House plan/architecture
Actual built house
Count
Only one class definition
Many objects from one class
// Class — blueprint (defined once)
class Car {
String brand;
int speed;
void drive() { System.out.println("driving " + brand); }
}
// Objects — instances (created many times)
Car c1 = new Car(); c1.brand = "Tesla";
Car c2 = new Car(); c2.brand = "BMW";
// c1 and c2 are separate objects of the same class
🟡 DBMS — Q25 to Q36
Q25. ⭐ What is normalization? Explain 1NF, 2NF, 3NF, and BCNF.
Answer: Normalization organises a database to reduce data redundancy and improve data integrity.
1NF (First Normal Form):
Atomic values — no multi-valued or composite attributes
Each column has a single value per row
Violation: Phone: 9876543210, 9123456789 in one cell
2NF (Second Normal Form):
Must be 1NF
No partial dependency — every non-key attribute must depend on the FULL primary key
Applies only to composite primary keys
3NF (Third Normal Form):
Must be 2NF
No transitive dependency — non-key column should NOT depend on another non-key column
Example violation: EmpID → Dept → DeptLocation (DeptLocation depends on Dept, not EmpID)
BCNF (Boyce-Codd Normal Form):
Stronger version of 3NF
For every functional dependency X → Y, X must be a super key
Q26. ⭐ What is the difference between a primary key and a unique key?
Q27. ⭐ What is a foreign key? What is referential integrity?
Answer: A foreign key is a column in one table that references the primary key of another table. It creates a link between two tables.
Referential Integrity ensures that:
You cannot insert a foreign key value that doesn’t exist in the referenced table
You cannot delete a primary key row that is referenced by a foreign key (unless CASCADE is set)
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id)
ON DELETE CASCADE -- delete orders when customer is deleted
ON UPDATE CASCADE -- update if customer id changes
);
Q28. ⭐ What are the two integrity rules in DBMS?
Answer:(Actual TCS Prime question — PrepInsta)
1. Entity Integrity Rule: Every table must have a primary key, and the primary key column cannot contain NULL values. Every row must be uniquely identifiable.
2. Referential Integrity Rule: Foreign key values must either:
Match a primary key value in the referenced table, OR
Be NULL
This prevents orphaned records — you cannot have an Order referencing a Customer that doesn’t exist.
Q29. ⭐ What is a transaction in DBMS? What are ACID properties?
Answer: A transaction is a sequence of database operations treated as a single logical unit.
A — Atomicity: All-or-nothing. If any step fails, the entire transaction rolls back. Example: Bank transfer — deduct from A AND credit to B must both succeed or both fail.
C — Consistency: Transaction takes DB from one valid state to another, maintaining all constraints.
I — Isolation: Concurrent transactions don’t interfere. Intermediate states are invisible to others.
D — Durability: Once committed, changes are permanent — survive system crashes (via write-ahead log).
Q30. ⭐ What is a view in SQL? What are its advantages?
Answer: A view is a virtual table based on a SELECT query. It doesn’t store data physically — it stores the query definition.
-- Create a view
CREATE VIEW high_earners AS
SELECT name, department, salary
FROM employees
WHERE salary > 80000;
-- Use it like a table
SELECT * FROM high_earners WHERE department = 'Engineering';
Advantages:
Security — hide sensitive columns from users
Simplification — complex queries stored once, reused as simple table
Data abstraction — underlying table structure can change without affecting users
Q31. ⭐ What is the difference between clustered and non-clustered index?
Answer:
Clustered Index
Non-Clustered Index
Data storage
Data physically sorted on disk
Separate structure pointing to data
Count per table
Only ONE
Multiple allowed
Speed
Faster for range queries
Slightly slower (extra pointer lookup)
Default
Created for primary key
Created with CREATE INDEX
-- Clustered (primary key creates it automatically)
CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(50));
-- Non-clustered
CREATE INDEX idx_name ON emp(name);
CREATE INDEX idx_dept_sal ON emp(department, salary); -- composite
Q32. ⭐ What is a trigger in SQL? When is it used?
Answer: A trigger is a stored procedure that automatically executes in response to a DML event (INSERT, UPDATE, DELETE) on a table.
-- Trigger: log salary changes
CREATE TRIGGER log_salary_change
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary_audit(emp_id, old_salary, new_salary, changed_at)
VALUES (OLD.id, OLD.salary, NEW.salary, NOW());
END;
Types:
BEFORE / AFTER triggers
ROW-level / Statement-level triggers
Use cases: Audit logging, enforcing business rules, auto-updating derived columns, cascading changes.
Q33. ⭐ What is a stored procedure? How is it different from a function?
Answer:
Stored Procedure
Function
Return value
Optional (0 or more)
Must return ONE value
Usage
Called with CALL/EXECUTE
Used in SELECT, WHERE
DML inside
Yes
Limited (depends on DB)
Exception handling
Yes
Limited
Purpose
Business logic
Computation/calculation
-- Stored procedure
CREATE PROCEDURE get_employees_by_dept(IN dept_name VARCHAR(50))
BEGIN
SELECT * FROM employees WHERE department = dept_name;
END;
CALL get_employees_by_dept('Engineering');
-- Function
CREATE FUNCTION get_annual_salary(monthly DECIMAL(10,2))
RETURNS DECIMAL(10,2)
BEGIN
RETURN monthly * 12;
END;
SELECT name, get_annual_salary(salary) FROM employees;
Q34. ⭐ What is a cursor in SQL?
Answer: A cursor is a database object used to retrieve and process rows one at a time from a result set (like a pointer/iterator for query results).
DECLARE emp_cursor CURSOR FOR
SELECT name, salary FROM employees WHERE dept = 'IT';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN emp_cursor;
read_loop: LOOP
FETCH emp_cursor INTO v_name, v_salary;
IF done THEN LEAVE read_loop; END IF;
-- process each row
SET v_salary = v_salary * 1.10;
UPDATE employees SET salary = v_salary WHERE name = v_name;
END LOOP;
CLOSE emp_cursor;
When to use: When row-by-row processing is required and set-based operations are not possible. Generally avoided due to performance overhead.
Q35. ⭐ What is ER (Entity-Relationship) model?
Answer: An ER model is a conceptual diagram that describes the structure of a database using entities, attributes, and relationships.
Relationship — Association between entities (Employee WORKS_IN Department)
Cardinality — 1:1, 1:M, M:M relationships
Types of entities:
Strong entity — Has its own primary key
Weak entity — Depends on another entity (OrderItem depends on Order)
Q36. ⭐ What is denormalization? When would you use it?
Answer: Denormalization is the process of intentionally adding redundancy to a database that was previously normalized, to improve read performance.
When to use:
Read-heavy systems where query speed matters more than storage
Data warehouses and reporting databases
When complex JOINs across many tables are too slow
-- Normalized: need JOIN to get product name with order
SELECT o.id, p.name FROM orders o JOIN products p ON o.product_id = p.id;
-- Denormalized: product_name stored directly in orders table
SELECT id, product_name FROM orders; -- no JOIN needed, faster
Trade-off: Denormalization sacrifices storage efficiency and data consistency for query speed.
🟢 OPERATING SYSTEMS — Q37 to Q46
Q37. ⭐ What is an operating system? What are its main functions?
Answer: An OS is system software that manages hardware resources and provides services to application programs. It acts as an interface between user and hardware.
Main functions:
Process Management — Create, schedule, terminate processes
Advantage: Fair, no starvation. Disadvantage: High context switching overhead if quantum is too small; long waiting time if quantum is too large.
Q42. ⭐ What is virtual memory? What is thrashing?
Answer:Virtual memory is a technique that allows executing processes that may not be completely in memory. It uses disk space as an extension of RAM.
When a process references a page not in RAM → Page Fault → OS brings the page from disk (page swapping).
Thrashing occurs when a system spends more time swapping pages in and out of memory than executing actual instructions.
Causes: Too many processes running simultaneously with insufficient RAM. Solution: Reduce degree of multiprogramming, increase RAM, use working set model.
Q43. ⭐ What is the difference between internal and external fragmentation?
Answer:
Internal Fragmentation — Wasted space inside allocated memory blocks. Occurs in fixed-size allocation (paging). If a process needs 18KB and gets 20KB pages → 2KB wasted inside.
External Fragmentation — Wasted space outside allocated memory — enough total free memory exists but not as a contiguous block. Occurs in variable-size allocation (segmentation).
Q44. ⭐ What are semaphores? What is the difference between binary and counting semaphores?
Answer: A semaphore is a synchronisation primitive (integer variable) used to control access to shared resources in a concurrent system.
Operations:
wait(S) / P(S): Decrements S; blocks if S = 0
signal(S) / V(S): Increments S; wakes up blocked process
Binary Semaphore (Mutex):
Value: 0 or 1 only
Used for mutual exclusion (one process at a time)
Equivalent to a lock
Counting Semaphore:
Value: 0 to N
Controls access to a resource pool of N instances
Example: DB connection pool of 10 connections → semaphore initialised to 10
Q45. ⭐ What is context switching?
Answer: Context switching is the process of saving the state of a currently running process and loading the state of the next process so the CPU can switch between processes.
State saved/restored (Process Control Block — PCB):
Program Counter (next instruction address)
CPU registers
Memory management info
Process state (running, waiting, ready)
Cost: Context switching is pure overhead — CPU does no useful work during the switch. High frequency switching wastes CPU cycles. This is why threads are preferred over processes for concurrency (cheaper context switch).
Q46. ⭐ What is the difference between multiprogramming, multitasking, and multiprocessing?
Answer:
Multiprogramming
Multitasking
Multiprocessing
Definition
Multiple programs in memory
Multiple tasks sharing CPU (time-sharing)
Multiple CPUs executing simultaneously
Goal
Maximise CPU utilisation
Improve responsiveness to users
True parallelism
CPU count
One
One
Multiple
Example
Batch OS
Modern desktop OS
Multi-core processor
🔵 COMPUTER NETWORKS — Q47 to Q56
Q47. ⭐ Explain the OSI model with all 7 layers.
Answer:
Layer
Name
Function
Protocol/Example
7
Application
User interface, app services
HTTP, HTTPS, FTP, DNS, SMTP
6
Presentation
Data formatting, encryption, compression
SSL/TLS, JPEG, ASCII
5
Session
Establish, manage, terminate sessions
NetBIOS, RPC
4
Transport
End-to-end delivery, error control, flow control
TCP, UDP
3
Network
Logical addressing, routing
IP, ICMP, ARP
2
Data Link
Physical addressing (MAC), error detection
Ethernet, Wi-Fi (802.11)
1
Physical
Raw bit transmission over physical medium
Cables, Hubs, Repeaters
Memory trick: “All People Seem To Need Data Processing” (bottom to top: Physical, Data Link, Network, Transport, Session, Presentation, Application)
Q48. ⭐ What is the difference between TCP and UDP?
Answer:
TCP
UDP
Connection
Connection-oriented (handshake)
Connectionless
Reliability
Guaranteed delivery, ACK
No guarantee
Order
Maintains order
No ordering
Speed
Slower
Faster
Header size
20 bytes
8 bytes
Use case
File transfer, web, email
Live streaming, gaming, DNS
TCP 3-way handshake:
Client → SYN → Server
Client ← SYN-ACK ← Server
Client → ACK → Server
[Connection established]
Q49. ⭐ What is an IP address? What is the difference between IPv4 and IPv6?
Answer: An IP address is a numerical label assigned to each device on a network that uses the Internet Protocol for communication.
IPv4
IPv6
Length
32 bits
128 bits
Format
Dotted decimal: 192.168.1.1
Hexadecimal: 2001:0db8:85a3::8a2e:0370:7334
Addresses
~4.3 billion
~340 undecillion
NAT required
Yes (due to shortage)
No
Header
20 bytes (min)
40 bytes (fixed)
Q50. ⭐ What is a firewall? How is it different from IDS/IPS?
Answer:(Actual TCS Prime question — PrepInsta)
Firewall — Network security device that monitors and controls incoming/outgoing traffic based on predefined rules. Operates at Layer 3/4 of OSI. Blocks/allows packets based on IP, port, protocol.
IDS (Intrusion Detection System) — Monitors network traffic for suspicious activity and alerts administrators. Passive — doesn’t block.
IPS (Intrusion Prevention System) — Like IDS but actively blocks threats in real-time. Inline device.
Firewall
IDS
IPS
Action
Block/Allow
Alert only
Alert + Block
Position
Network perimeter
Monitor mode
Inline
Threat type
Known rule violations
Anomalies/signatures
Both
Q51. ⭐ What is DNS? How does it work?
Answer:DNS (Domain Name System) translates human-readable domain names (www.google.com) into IP addresses (142.250.195.36).
DNS Resolution process:
User types www.google.com
Browser checks local cache — if found, done
Query goes to Recursive Resolver (usually ISP’s DNS)
Resolver queries Root Name Server → points to .com TLD server
TLD server → points to google.com Authoritative Name Server
Authoritative server → returns IP address 142.250.195.36
Browser connects to that IP
DNS record types: A (IPv4), AAAA (IPv6), CNAME (alias), MX (mail), TXT (verification)
Q52. ⭐ What is the difference between HTTP and HTTPS?
Answer:
HTTP
HTTPS
Full form
HyperText Transfer Protocol
HTTP Secure
Security
No encryption
Encrypted via SSL/TLS
Port
80
443
Certificate
Not required
SSL/TLS certificate required
Data exposure
Transmitted as plain text
Encrypted
Use case
Non-sensitive public content
Login, payments, banking
How HTTPS works:
Client requests HTTPS connection
Server sends SSL certificate
Client verifies certificate (CA signed?)
Client generates session key, encrypts with server’s public key
Server decrypts with private key
Encrypted communication begins using session key
Q53. ⭐ What is a MAC address? How is it different from an IP address?
Answer:
MAC Address
IP Address
Full form
Media Access Control
Internet Protocol
Layer
Data Link (Layer 2)
Network (Layer 3)
Assigned by
Manufacturer (hardcoded)
Network admin or DHCP
Uniqueness
Globally unique per device
Unique within network
Changeability
Cannot be changed (normally)
Can be changed
Format
48-bit, e.g., AA:BB:CC:DD:EE:FF
32-bit (IPv4): 192.168.1.1
Purpose
Local network delivery
Cross-network delivery
Q54. ⭐ What is the difference between a router, switch, and hub?
Answer:
Hub
Switch
Router
Layer
Physical (1)
Data Link (2)
Network (3)
Addressing
None (broadcasts all)
MAC address
IP address
Traffic
Broadcasts to all ports
Sends to specific port
Routes between networks
Intelligence
None
Medium
High
Collision domain
One for all ports
One per port
Separate per interface
Use case
Legacy/obsolete
LAN within organisation
Connect LAN to internet
Q55. ⭐ What is the concept of subnetting?
Answer: Subnetting is the process of dividing a large network into smaller sub-networks (subnets) to improve performance, security, and address management.
Q57. ⭐ Write a program to reverse a linked list. (Actual TCS Prime — paper coding)
Answer:
class Node:
def __init__(self, val):
self.val = val
self.next = None
def reverse(head):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev # new head
# Time: O(n) Space: O(1)
Q58. ⭐ Write a program to find if a number is prime. (Actual TCS TR — paper coding)
Answer:
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
# Optimised: only check up to sqrt(n)
# Time: O(sqrt(n))
Q59. ⭐ Write a program to find all words with more than 8 characters in a sentence. (Actual TCS Digital — paper coding)
Answer:
sentence = "TCS is a multinational technology company headquartered in Mumbai"
result = [w for w in sentence.split() if len(w) > 8]
print(result)
# Output: ['multinational', 'technology', 'headquartered']
Q60. ⭐ Write a program to find the frequency of each character in a string. (Actual TCS TR — paper coding)
Answer:
def char_frequency(s):
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
for ch, count in sorted(freq.items()):
print(f"'{ch}': {count}")
char_frequency("programming")
# 'a': 1, 'g': 2, 'i': 1, 'm': 2, 'n': 1, 'o': 1, 'p': 1, 'r': 2
Q61. ⭐ Write a program to find the square root of a number without using sqrt(). (Actual TCS Prime — exact PYQ)
Answer:
def sqrt_binary(n):
if n < 2:
return n
low, high, ans = 1, n // 2, 0
while low <= high:
mid = (low + high) // 2
if mid * mid == n:
return mid
elif mid * mid < n:
ans = mid
low = mid + 1
else:
high = mid - 1
return ans # floor of sqrt
print(sqrt_binary(6096)) # 78
print(sqrt_binary(25)) # 5
# Time: O(log n)
Q62. ⭐ Print a star pattern (N rows triangle). (Actual TCS TR — paper coding)
Answer:
n = 5
# Right triangle
for i in range(1, n + 1):
print('* ' * i)
# Output:
# *
# * *
# * * *
# * * * *
# * * * * *
# Pyramid pattern
for i in range(1, n + 1):
print(' ' * (n - i) + '* ' * i)
Q63. ⭐ Write a program to check if a string is a palindrome. (Actual TCS TR)
Answer:
def is_palindrome(s):
s = s.lower().replace(' ', '') # clean input
return s == s[::-1]
print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False
print(is_palindrome("A man a plan a canal Panama")) # True
Q64. ⭐ Write code to find the length of the Longest Palindromic Subsequence. (Actual TCS Prime — exact PYQ from GeeksforGeeks)
Answer:
def lps(s):
n = len(s)
t = s[::-1] # reverse = LCS trick
dp = [[0]*(n+1) for _ in range(n+1)]
for i in range(1, n+1):
for j in range(1, n+1):
if s[i-1] == t[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[n][n]
print(lps("bbabcbcab")) # 7 ("babcbab")
# Time: O(n^2) Space: O(n^2)
Q65. ⭐ Write code to create an upper triangular matrix. (Actual TCS Prime — exact coding PYQ)
Answer:
def upper_triangular(matrix):
n = len(matrix)
for i in range(n):
for j in range(n):
if j < i:
matrix[i][j] = 0
return matrix
mat = [[1,2,3],[4,5,6],[7,8,9]]
result = upper_triangular(mat)
for row in result:
print(row)
# [1, 2, 3]
# [0, 5, 6]
# [0, 0, 9]
Q66. ⭐ Write code for Binary Search. (Actual TCS Digital TR — paper coding)
Answer:
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid # found at index mid
elif arr[mid] < target:
low = mid + 1 # search right half
else:
high = mid - 1 # search left half
return -1 # not found
arr = [1, 3, 5, 7, 9, 11, 13]
print(binary_search(arr, 7)) # 3
print(binary_search(arr, 6)) # -1
# Time: O(log n)
Q67. ⭐ Write code to detect a cycle in a linked list. (Actual TCS Prime — paper coding)
Answer:
class Node:
def __init__(self, val):
self.val = val
self.next = None
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next # move 1 step
fast = fast.next.next # move 2 steps
if slow == fast:
return True # cycle detected
return False
# Floyd's Tortoise and Hare Algorithm
# Time: O(n) Space: O(1)
Q68. ⭐ Write code to implement a stack using an array. (Actual TCS Digital TR)
Answer:
class Stack:
def __init__(self, capacity):
self.stack = []
self.capacity = capacity
def push(self, val):
if len(self.stack) == self.capacity:
print("Stack Overflow")
return
self.stack.append(val)
def pop(self):
if not self.stack:
print("Stack Underflow")
return None
return self.stack.pop()
def peek(self):
return self.stack[-1] if self.stack else None
def is_empty(self):
return len(self.stack) == 0
s = Stack(3)
s.push(10); s.push(20); s.push(30)
print(s.pop()) # 30
print(s.peek()) # 20
Q69. ⭐ Write a program to demonstrate abstraction using OOP. (Actual TCS Digital — exact coding question)
Q70. ⭐ Write code to find the Fibonacci series using both recursion and dynamic programming. (Actual TCS TR — exact PYQ)
Answer:
# Method 1: Recursion (simple, exponential time)
def fib_recursive(n):
if n <= 1: return n
return fib_recursive(n-1) + fib_recursive(n-2)
# Time: O(2^n) — very slow for large n
# Method 2: Dynamic Programming (memoisation)
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n <= 1: return n
return fib_memo(n-1) + fib_memo(n-2)
# Time: O(n) Space: O(n)
# Method 3: DP Tabulation (most efficient)
def fib_dp(n):
if n <= 1: return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
# Time: O(n) Space: O(n)
print([fib_dp(i) for i in range(10)])
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
🧠 BEHAVIOURAL + SCENARIO — Q71 to Q82
Q71. ⭐ Tell me about a time you failed. What did you learn?
Answer (STAR):Situation: In my 3rd semester, I was overconfident going into the database design exam and didn’t revise thoroughly.
Task: Score well and understand relational design concepts deeply.
Action: I failed to account for a complex normalisation question. After the exam, I didn’t make excuses — I revisited the entire topic, built a small database project from scratch, and taught it to a classmate to reinforce my understanding.
Result: In my next related exam I scored 92%. More importantly, DBMS became one of my strongest interview topics. Failure taught me that confidence without preparation is arrogance.
Q72. ⭐ Describe a project you are most proud of. Walk me through it technically.
Answer (Framework):
Problem statement — What problem did it solve?
Tech stack — Languages, frameworks, databases used
Architecture — How the system was designed (frontend → backend → DB)
Your specific contribution — Not the team’s work, YOUR work
Challenges faced — Technical hurdles and how you overcame them
Sample opening: “My most proud project is a real-time attendance management system I built using Flask, SQLite, and OpenCV for face recognition. The problem was our college’s manual attendance was error-prone and time-consuming. I designed the database schema, built the REST API, and integrated face detection — which was my biggest challenge because accuracy dropped in low-light conditions. I solved it by adding image preprocessing…”
Q73. ⭐ How do you handle disagreements with teammates or a senior?
Answer: “I believe disagreements are healthy when handled constructively. My approach is to first ensure I fully understand the other person’s point — I listen completely before responding. If I disagree with a senior, I frame it professionally: ‘I see your point, may I share a concern?’ and present data or reasoning to support my view. If the disagreement is with a peer, I suggest we take both approaches to a smaller test scenario and let results decide. I’ve found that separating the idea from the person makes technical disagreements much easier to resolve. Ultimately, I defer to hierarchy when a decision must be made, but I always ensure my concern is documented.”
Q74. ⭐ Give an example where you showed leadership.
Answer (STAR): “During our final year project, our team of four had unclear responsibilities and we were behind schedule two weeks before the deadline. I recognised that nobody had taken ownership, so I stepped up — I called a meeting, mapped out remaining tasks, assigned them based on each person’s strengths, and set daily check-in deadlines. I also paired the weakest team member with myself for the database component so nothing would block progress. We submitted on time with a complete feature set. Our guide complimented the project’s quality. This taught me that leadership isn’t about authority — it’s about taking responsibility when others hesitate.”
Q75. ⭐ What would you do if you were given an impossible deadline?
Answer: “My first step would be to break the task down and get a realistic estimate of what’s achievable. I would immediately communicate transparently with my manager: ‘Here is what can be delivered by X date and here is what cannot — what is the priority?’ I would not promise something I cannot deliver and then fail silently. I believe setting honest expectations early is far better than delivering incomplete work at the last minute. I would also look for ways to optimise — reduce scope, automate repetitive tasks, or ask for temporary resources. If the deadline genuinely cannot move, I would work extended hours for a short sprint but flag that this isn’t sustainable long-term.”
Q76. ⭐ You have a bug in production that is affecting thousands of users. What do you do?
Answer: “Step one is immediate containment — if there’s a rollback available, I roll back to the last stable version while we investigate. If not, I check if the bug can be patched with a hotfix in under an hour. Step two is identification — I look at logs, error reports, and replicate the issue locally. Step three is communication — I inform the team lead immediately and provide a clear status update. I never go silent during an incident. Step four is fix and test — write the fix, test it in staging, then deploy with monitoring. Step five is post-mortem — after resolution, I document what went wrong, why, and what preventive measure stops it from happening again.”
Q77. ⭐ How do you prioritise tasks when you have multiple deadlines?
Answer: “I use a combination of urgency and importance — the Eisenhower Matrix approach. I first identify what’s truly urgent AND important (do immediately), what’s important but not urgent (schedule), what’s urgent but not important (delegate if possible), and what’s neither (drop or defer). I also consider dependencies — which task blocks others. I communicate early if I think something is at risk. In practice, I maintain a task list with deadlines and estimate time per task at the start of each day. This visual clarity prevents the feeling of being overwhelmed and ensures I’m making conscious priority decisions rather than reactive ones.”
Q78. ⭐ Tell me about a time you had to learn something very quickly.
Answer (STAR): “Situation: During my internship, I was suddenly assigned to a task that required React.js — a framework I hadn’t formally learned.
Task: Build a dashboard component in one week.
Action: I spent the first day going through the official React docs and building a mini to-do app. On day 2, I started the actual task with a simplified scope and gradually added complexity. I asked targeted questions to senior developers rather than general ‘how does React work’ questions.
Result: I delivered the dashboard component within 5 days. My manager said it was ‘production-ready’ with minor tweaks. This experience reinforced my belief that the fastest way to learn a technology is to build something real with it immediately.”
Q79. ⭐ What is your biggest strength? How does it apply to software engineering?
Answer: “My biggest strength is structured problem decomposition — the ability to take a complex problem and break it into smaller, manageable parts before writing a single line of code. In software engineering, this directly maps to system design, where rushing to code without clarity creates technical debt. When I face a difficult coding problem, I spend the first 20% of the time understanding and decomposing it — drawing the flow, identifying edge cases, planning the data structures — before I write anything. This approach consistently produces cleaner solutions. It also helps me communicate clearly with non-technical stakeholders, because I can translate a complex system into understandable components.”
Q80. ⭐ If a team member is not contributing and it’s affecting your project, what will you do?
Answer: “I would first try to understand if there’s a genuine reason — personal issues, lack of clarity on tasks, skill gaps. I would have a private, non-judgmental conversation: ‘I noticed you’ve been quiet on the project — is there anything I can help with?’ Many times, people are struggling silently. If it’s a skills gap, I would offer to pair with them. If they are simply disengaged, I would have an honest conversation: ‘Our deadline is X and we need Y from you specifically.’ If the issue persists and starts genuinely risking the project, I would escalate to the team lead — not to get them in trouble, but because the project’s success and the entire team’s effort deserves protection.”
Q81. ⭐ Are you comfortable working in a team or alone? Which do you prefer?
Answer: “I work effectively in both environments and adapt based on what the situation demands. For creative and exploratory tasks — like architecting a solution or debugging a tricky problem — I do my best thinking independently. For execution, review, and iteration — sharing code, discussing approaches, catching each other’s blind spots — a team is far superior. In a professional setting, both skills are essential. My internship gave me experience in a cross-functional team of 6, and I’ve also completed significant solo projects. I’m genuinely comfortable in both modes.”
Q82. ⭐ How do you stay updated with technology trends?
Answer: “I have a structured approach. For daily updates I follow specific newsletters — TLDR Tech, The Pragmatic Engineer. For deep dives I use official documentation, YouTube channels like Fireship, and read tech blogs from companies like Netflix Engineering, Uber Engineering, and Google Research. I try to build something small with any new technology I read about — theory without practice is forgettable. I’m also active on GitHub, where I explore popular open-source repositories to understand how production-level code is structured. Recently I’ve been tracking developments in vector databases and RAG systems for AI applications.”
📊 MANAGERIAL ROUND — Q83 to Q91
Q83. ⭐ What is your opinion on Work From Home vs Work From Office?
Answer: “Both modes have genuine strengths. Office work is invaluable early in a career — the informal knowledge transfer, mentorship, and cultural absorption that happen organically in an office are very difficult to replicate remotely. For a fresher joining TCS, the office environment would accelerate my learning significantly. Remote work, on the other hand, offers focused deep-work time, eliminates commute, and can be more productive for autonomous tasks. I believe a hybrid model captures the best of both. I am completely adaptable to whatever model TCS requires for my project, and I’ve already practiced self-discipline through online learning and solo project work.”
Q84. ⭐ If we give you a technology you have never worked with, how will you handle it?
Answer: “I would treat it as an opportunity rather than a challenge. My approach is: first, spend a day with the official documentation to understand the core concepts and mental model of the technology. Second, build the smallest possible working program — even a ‘Hello World’ equivalent for that technology — to break the psychological barrier. Third, attempt a simplified version of the actual task. Fourth, use targeted questions to seniors or communities like Stack Overflow for specific blockers — never general ‘how does X work’ questions.
I learned Python this way in three weeks while already knowing C and Java. The underlying concepts — variables, loops, functions, OOP — transfer across languages. What changes is syntax and idioms, and those are learnable quickly with practice.”
Q85. ⭐ If we downgrade your offer from Digital to Ninja, would you accept?
Answer: “I appreciate you being direct with this question. I’ll be equally direct — my preparation, the profile I interviewed for, and my career expectations are aligned with the Digital profile. I wouldn’t want to start my career at TCS under the wrong expectations on either side.
That said, I genuinely want to work at TCS. If there is a clear path and timeline to transition to Digital based on performance, and if the work I’d be doing as a Ninja fresher gives me meaningful exposure, I’d want to understand that roadmap clearly before deciding. I believe in making informed decisions rather than emotional ones.”
Q86. ⭐ You are from ECE. Why did you choose IT over core electronics?
Answer: “ECE gave me a strong foundation in systems thinking, embedded logic, and how hardware and software interact at the fundamental level. During my second year, I built a project that combined sensors with a web dashboard — that intersection of hardware and software was what drew me to programming. I realised that software could reach millions of people in a way that hardware products alone couldn’t.
Since then, I’ve deliberately built my software skills — DSA, web development, databases, and system design. My ECE background is actually an advantage in IT, especially for roles involving IoT, embedded systems, or cloud-connected hardware. I see it as a complement, not a compromise.”
Q87. ⭐ What do you know about TCS’s business and current initiatives?
Answer: “TCS is India’s largest IT services company by market capitalisation — approximately $168 billion as of early 2025 — and consistently one of the top 10 IT companies globally. TCS operates in 46 countries with over 600,000 employees.
Currently, TCS is heavily investing in AI through its TCS.AI platform, offering GenAI services to enterprise clients. Their TCS Pace innovation hubs focus on quantum computing, cloud, and AI research. TCS has significant presence in BFSI, healthcare, retail, and government sectors. Recent wins include major cloud transformation deals with European financial institutions and a long-term partnership with Jaguar Land Rover. Their iON platform handles large-scale digital assessments, and BaNCS is a leading banking product used globally.”
Q88. ⭐ If your manager gives you a task you disagree with technically, what will you do?
Answer: “My first step is to make sure I fully understand the reasoning — sometimes a technical decision that looks wrong has context I’m missing. I would ask: ‘Could you help me understand the constraints driving this approach?’ If after understanding their perspective I still have a genuine concern, I would raise it professionally: ‘I understand your approach. I have a concern about X — may I share it?’ and back it with data, benchmarks, or a concrete example.
If my concern is heard but overruled, I’d accept the decision and execute it to the best of my ability — expressing disagreement and then delivering poorly is worse than just complying. However, I would document my concern so if an issue arises later there’s a record. Healthy technical disagreement expressed respectfully is what separates good engineers from yes-men.”
Q89. ⭐ How would you handle a very difficult client who is never satisfied?
Answer: “Difficult clients are usually driven by unmet expectations, not personality. My approach would be to first understand exactly what ‘satisfied’ means to them — what specific outcome would make them happy? Often, frustration comes from vague requirements that led to vague delivery.
I would set up a structured communication cadence — weekly updates with concrete metrics, not general ‘we’re working on it’ updates. I would involve them in milestone reviews so they see progress incrementally rather than only at final delivery. If expectations are genuinely unreasonable, I would involve my manager early — never promise what cannot be delivered just to keep peace in the short term. Ultimately, a good client relationship is built on predictability and honesty, not just saying yes.”
Q90. ⭐ Where do you see yourself in 5 years?
Answer: “In five years I want to be a technically strong engineer with deep expertise in at least one domain — my current interest is in cloud-native systems and distributed architecture. I want to have contributed meaningfully to at least 2–3 end-to-end enterprise projects, preferably with client-facing exposure. At TCS, that would put me at the IT Analyst or Assistant Consultant level on the technical track.
Beyond titles, I want to be someone my team comes to for technical guidance — not because I’m the most senior, but because I’ve consistently delivered quality work and mentored others. I’m committed to continuous learning through TCS’s internal training platforms and relevant cloud certifications.”
Q91. ⭐ What motivates you when work becomes repetitive or boring?
Answer: “I look for the hidden learning within repetition. Even in repetitive tasks, there’s usually a way to optimise, automate, or refactor — finding that keeps me engaged. If I’m doing the same data transformation daily, I’ll write a script that does it in seconds. That’s how many great tools get built.
If the task is genuinely unavoidable and repetitive with no room for optimisation, I stay motivated by connecting it to the bigger outcome — ‘this report I’m generating matters to the client’s decision-making.’ I’m also honest with myself — if I’ve been on the same work for a long time with no growth, I’d have a conversation with my manager about new opportunities, because intellectual stagnation doesn’t serve either me or the company.”
🤝 HR + PERSONAL — Q92 to Q100
Q92. ⭐ Why should we hire you?
Answer: “You should hire me because I bring three things that matter specifically for TCS Digital: technical depth in the areas you test for — OOPs, DSA, databases, and systems — demonstrated through my consistent preparation and [specific project/achievement]. Second, I have a genuine curiosity about technology that means I’ll keep learning without being pushed to. Third, I communicate well — I can explain technical concepts to non-technical people, which matters in a client-facing organisation like TCS.
I’m not just looking for a job. I want to build a career at TCS, and I’ve been deliberately preparing for this profile, not applying everywhere and hoping something sticks.”
Q93. ⭐ What is your biggest weakness?
Answer: “My biggest weakness is that I sometimes over-engineer solutions — I tend to think about edge cases and scalability even when the immediate requirement doesn’t need them. This can slow down delivery of simple tasks.
I’ve been actively working on this by setting internal scope boundaries before I start coding: ‘For this task, good enough is X — don’t go beyond it unless asked.’ This has significantly improved my delivery speed. I’ve learned that premature optimisation, as the saying goes, is the root of all evil — there’s a time for robustness and a time for speed.”
Q94. ⭐ Tell me about yourself.
Answer (Structure): “My name is [Name]. I’m a [Branch] engineering graduate from [College]. I chose engineering because [genuine reason], and I gravitated toward software during [specific moment/project].
Technically, I’m strongest in [2–3 skills], and I have hands-on experience through [project/internship] where I [specific achievement]. My most meaningful technical work was [one project], where I [what you built, what problem it solved].
Beyond academics, I [relevant extra-curricular that shows discipline or curiosity]. I applied to TCS Digital specifically because [genuine specific reason related to TCS’s work]. I’m excited about the opportunity to contribute to [specific TCS domain/project type].”
Q95. ⭐ Do you have any other offer? How are you deciding between companies?
Answer: “Yes, I have [/I’m in the process with] [Company X]. My decision criteria are: the quality of technical work I’d be doing in the first 2 years, the learning infrastructure available, the company’s scale and global presence, and the team culture.
TCS stands out because of its scale — working on systems that serve millions of users is genuinely different from smaller environments, and that exposure early in a career is invaluable. The TCS Digital profile specifically, with its focus on emerging technologies, aligns with the kind of engineering I want to do.
I haven’t decided yet but TCS Digital is my top preference.”
Q96. ⭐ Are you comfortable with night shifts or extended working hours when required?
Answer: “Yes, I understand that the nature of enterprise IT delivery — especially with global clients across time zones — sometimes requires flexibility in working hours. I’m comfortable with that, especially for time-bound deliverables like go-live support or production incidents. I believe this kind of commitment is part of what makes a professional reliable.
That said, I also value sustainable work practices for long-term productivity. I’d aim to ensure that extended hours are the exception for genuine business needs rather than a substitute for poor planning. I’m committed to doing what the role requires.”
Q97. ⭐ How do you rate yourself in your favourite programming language on a scale of 1–10?
Answer: “I’d rate myself a 7.5 in Python — my strongest language. I’m very comfortable with core Python: data structures, OOP principles, file handling, generators, decorators, and standard libraries. I’ve used it for [projects].
I rate myself 7.5 and not higher because there are areas I’m still actively developing — asynchronous programming with asyncio, metaclasses, and some performance profiling tools. I believe a 9 or 10 would mean there’s nothing left to learn, which is never true in any technology. I prefer honest self-assessment — I know what I know and I know what I don’t.”
Q98. ⭐ What are your hobbies? How do they relate to your professional life?
Answer: “Outside of academics, I enjoy [genuine hobby]. If it’s technical: ‘I enjoy contributing to open-source projects on GitHub — it has taught me how to read and understand codebases I didn’t write, which is one of the most underrated professional skills.’ Or if non-technical: ‘I play chess, which has strengthened my ability to think multiple steps ahead before acting — something I directly apply when designing system architecture or debugging complex problems.’
[Connect the hobby to a professional trait — discipline, problem-solving, creativity, communication.] I believe who you are outside work shapes how you work, and I try to bring that intentionality to both.”
Q99. ⭐ Do you have any questions for us?
Answer: “Yes, I have three:
First — What does the onboarding and initial training journey look like for a Digital hire? How quickly would I be expected to work on client-facing projects?
Second — What technologies or domains are TCS Digital fresh hires currently being oriented toward — are there specific cloud platforms, AI stacks, or industry verticals that are growing?
Third — How does TCS evaluate performance during the first year for fresher engineers? What does a strong first-year trajectory look like from your observation?”
(Never ask about salary, leave policy, or work hours in the first interview.)
Q100. ⭐ What is the current market cap of TCS? Tell me something recent about TCS.
Answer:(Actual TCS Digital HR question — exact PYQ from PrepInsta Prime)
“As of March 2025, TCS’s market capitalisation is approximately $168 billion USD (around ₹14 lakh crore), making it consistently India’s most valuable company by market cap and one of the top global IT firms.
Recent TCS developments worth mentioning:
TCS launched its TCS.AI platform offering GenAI-powered enterprise services
TCS Pace Ports innovation hubs are actively researching quantum computing and cloud AI
TCS recently won a multi-year cloud transformation deal with a major European bank
Their BaNCS banking platform continues to dominate globally with new implementations
TCS employs over 600,000 people across 46+ countries — a testament to its scale
TCS has been working on eGovernance modernisation projects in India including the income tax portal”
COMPLETE 100-QUESTION MASTER REFERENCE
Category
Q#
Count
Round
🔷 SQL
Q1–Q12
12
TR
🟠 OOPs
Q13–Q24
12
TR
🟡 DBMS
Q25–Q36
12
TR
🟢 Operating Systems
Q37–Q46
10
TR
🔵 Computer Networks
Q47–Q56
10
TR
💻 Coding on Paper
Q57–Q70
14
TR
🧠 Behavioural + Scenario
Q71–Q82
12
TR/MR
📊 Managerial Round
Q83–Q91
9
MR
🤝 HR + Personal
Q92–Q100
9
HR
Final Preparation Strategy:
SQL: Practice writing queries by hand — no IDE help. Focus on JOINs, GROUP BY, subqueries, window functions
OOPs: Be able to write actual code for every concept, not just define it
DBMS: Normalization + ER diagrams + ACID are non-negotiable
OS: Deadlock, scheduling, paging — understand the WHY, not just definitions
Networks: OSI model + TCP/UDP + DNS flow — draw the diagrams
Coding: Practise on paper with a pen. No autocomplete, no Google
Behavioural: Prepare 5 real stories from your life using STAR format — reuse them across questions
HR: Research TCS’s recent news 24 hours before your interview
TCS NQT Last 7 Days Plan: Simple Guide That Every Student Can Follow
TCS NQT in 7 days? Here’s a simple day-by-day plan covering Logical, Verbal, Numerical and Coding — written in plain language for every student.
Your TCS NQT exam is just 7 days away.
You are tensed. You don’t know where to start. You feel like you have studied a lot but still not confident.
Don’t worry. That is completely normal.
This blog will tell you exactly what to do — topic by topic, day by day — in the simplest way possible. No big words. No confusing advice. Just a clear plan.
Let’s start.
First — Understand the New TCS NQT Pattern
Before you start studying, you need to know what has changed in TCS NQT 2026. Many students are still preparing for the old pattern. That is a big mistake.
Here are the 5 things you must know:
1. What is TITA? TITA means “Type In The Answer.” These are questions where you have to type the answer yourself. There are no options to choose from. So you cannot guess. You have to actually know the answer.
2. Foundation Section is NOT Easy Most students think Foundation is the easy section. But that is wrong. Foundation is actually quite difficult. Don’t ignore it.
3. Advanced Section is Easier Than You Think The Advanced section sounds scary. But if you practise the right topics, it is actually more scoring.
4. TCS Uses Previous Year Questions Yes! TCS repeats questions from previous years. So always practise PYQ (Previous Year Questions). That is why we have a 12-hour PYQ video in our free playlist.
5. There is Normalisation You don’t need to score 100%. TCS adjusts marks based on the difficulty of different exam slots. So relax and focus on doing your best — not on being perfect.
The 7-Day TCS NQT Preparation Schedule (The Game Changer)
Here’s the complete day-by-day breakdown. Each day is designed to maximize retention without burning you out.
Day 1–2: Logical Reasoning (Your Biggest Score Booster)
Logical Reasoning carries significant weightage in TCS NQT and is the most time-efficient section to improve — if you know what to focus on.
Must-cover topics:
Coding–Decoding (3–5 Questions) This is free marks if you practice patterns. Example:
If STRONG is written as ROTNSG, then NAGPUR = ?
The trick? Identify the positional swap pattern first, then apply it mechanically. Spend 20 minutes on 3 different pattern types.
Distance and Direction (2–3 Questions) Draw every question. Do not try to solve these in your head. A 30-second rough sketch saves 2 minutes of confusion.
Linear and Circular Arrangements (4–6 Questions) These are pure logic puzzles. Practice with 9-person linear rows and 8-person circular tables. The exam loves mixed conditions — “facing centre, second to the right of X, not adjacent to Y.”
Blood Relations (2–3 Questions) Master the +, –, × notation system. Once you decode the relationship symbols, these become the fastest questions in the section.
Syllogism and Assumptions (3–6 Questions) Know your Venn diagram approach cold. Practice: “Some A are B. All B are C.” — can you draw this in 10 seconds? You should be able to.
Number Series (3–6 Questions) Watch for: ×2+2, ×3–1, square/cube patterns, and alternating series. If a series looks random, check if it’s two interleaved series.
Resource: Watch the 7-Hour Logical Reasoning One Shot on YouTube — it covers all these patterns with actual TCS-style questions.
Day 3: Verbal Ability (Don’t Skip This — It’s Easier Than You Think)
Most students neglect Verbal Ability assuming it can’t be improved quickly. Wrong.
High-yield topics for TCS NQT:
Para Jumbles — Look for the sentence that introduces a concept (it’s usually the opener). Then find the logical flow.
Reading Comprehension — Read the questions before the passage. Answer only what’s asked. Don’t infer beyond the text.
Error Detection — Focus on subject-verb agreement, tense consistency, and preposition errors. These three cover 80% of errors.
Synonyms and Antonyms — Build a 50-word high-frequency list. Don’t try to memorize a dictionary.
Pro tip: Do a 1.5-hour Verbal One Shot and then immediately take a 20-question mock. Your retention doubles when you apply right away.
Day 4–5: Numerical Ability (The Section That Trips Everyone)
Numerical Ability in TCS NQT is not your school maths exam. It’s faster, trickier, and heavily DI-weighted. Here’s how to cover it efficiently:
Module 1 — Percentage, SI/CI, Profit & Loss These three are interlinked. Master percentage calculation shortcuts first — everything else becomes easier.
Module 2 — Ratio, Mixtures, Alligation, Ages & Averages Alligation is the most underrated shortcut in aptitude. Learn it once, use it forever for mixture and partnership problems.
Module 3 — Data Interpretation (High Priority) DI sets — tables, bar graphs, pie charts, caselets — appear in clusters. Practice reading data quickly and doing approximate calculations. Don’t calculate exact values when the options are spread apart.
Module 4 — Time and Work, Pipes and Cisterns Use the LCM method. It eliminates fractions and makes TW problems mechanical.
Module 5 — Permutation, Combination & Probability Know the basics: nPr, nCr, and complementary probability. TCS rarely goes deep here — they test fundamentals.
Module 6 — Time, Speed & Distance Relative speed for trains. Boats and streams. Average speed trap (don’t just average the speeds — use the harmonic mean formula).
TCS Favourites to memorise:
Quadratic equations shortcut
Mean, Median, Mode
Number system divisibility rules (2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
Mensuration formulas for 2D and 3D shapes
Simplification and approximation tricks
Resource: The Best 50 Numerical Questions video (2 Hours) on YouTube is gold — it covers the exact question types that repeat in TCS NQT.
Day 6: Coding (Don’t Panic — Be Strategic)
Coding is where most non-CS students freeze. Here’s the reality: you don’t need to be a DSA expert. You need to be pattern-aware.
What TCS NQT Coding actually tests:
Arrays — push zeros, leaders, subarrays
Strings — palindrome, anagram, frequency
Basic maths — digit sum, prime check, factorials
Story-based problems — chocolate factory, stock profit, handshake problem (combinatorics)
The actual exam has:
1–2 coding questions
Medium difficulty (not LeetCode Hard)
60–90 minutes total coding time
What to do on Day 6:
Watch the Actual TCS Coding One Shot (5 Hours) — covers real PYQ patterns
Practice the Story-Based Coding problems (2 Hours) — these are the most common exam format
Code at least 5 problems from scratch without looking at solutions
Languages: Python is fastest for implementation. Java works too. Choose what you’re comfortable with — don’t switch languages in the last week.
Day 7: Full Mock + Analysis (The Day Most Students Waste)
This is the day that separates toppers from average scorers.
Do NOT use Day 7 to revise new topics. That’s a panic move and it backfires.
Instead:
Take the All India Mock Test (4 Hours) — simulates the actual exam environment
Analyse every wrong answer — don’t just count your score, understand why you got it wrong
Identify your 3 weakest topic areas and do a 30-minute targeted revision on each
Scan your formula book — a quick pass through all formulas you’ve noted down
Sleep 8 hours — this is not optional; memory consolidation happens during sleep
The TCS NQT expected cut-off varies by batch and normalisation. Don’t aim for 100%. Aim for accuracy in your strong areas and time management overall.
The Most Important Rules for the Last 7 Days
These aren’t motivation quotes. They’re operational rules from people who’ve been through it.
1. Don’t finish one subject in one go. Divide every day: Logical + Quant + Verbal (Mock) + Technical + Live Sessions. Variety prevents burnout and improves retention.
2. Daily Mock + Analysis + Formula Scan is non-negotiable. Even if it’s just 20 questions — do a mock every single day. Your brain needs exam-mode practice, not just study-mode.
3. Is there a timer per question or per section? TCS uses section-wise timing. Know this going in. Manage your time per section, not per question.
4. Normalisation exists. Relax. TCS normalises scores across different exam slots. You don’t need a perfect score. You need a consistent, strategic performance.
5. Make your own timetable. No two students have the same strengths. Use this framework, but customise it. If Logical is your weak spot, give it Day 1 and Day 3. If Coding is your fear, revisit it on Day 7 morning.
The 8 YouTube Resources You Actually Need (Not 80)
Stop hoarding resources. Use these 8 and nothing else:
#
Resource
Duration
What It Covers
1
Logical Reasoning One Shot
7 Hours
Full LR syllabus
2
Logical Actual Paper
2 Hours
Real PYQ walkthrough
3
Numerical Ability Best 50
2 Hours
Top repeating questions
4
Actual TCS Coding One Shot
5 Hours
Full coding syllabus
5
All Story Based Coding
2 Hours
Story problem patterns
6
One Shot Verbal Ability
1.5 Hours
Full verbal section
7
All TCS PYQ Questions
12 Hours
Numerical + Logical PYQs
8
All India Mock Test
4 Hours
Full simulation
Total guided study time: ~35.5 hours across 7 days. That’s about 5 hours a day — intense but absolutely achievable.
🎯 FREE: The Only TCS NQT Playlist You’ll Ever Need
Before spending a single rupee on any course, start here.
CampusMonk’s FREE TCS NQT Playlist (40+ Hours) covers the entire syllabus — Logical, Verbal, Numerical, and Coding — with real PYQ walkthroughs and mock test strategies.
The formula is simple: FREE Playlist + Mock Test = Selection.
No shortcuts. No fluff. Just do both, consistently, for 7 days.
Critical Reasoning: The Hidden Marks Nobody Talks About
Syllogism and Assumptions (3–6 questions) are consistently underperformed by students who don’t practice them systematically.
Here’s a quick framework:
For Syllogism: Draw Venn diagrams for every question. Never try to solve syllogisms by logic alone — visualise them.
Example:
Some blue are black. Some black are grey. All grey are red. All red are pink.
Conclusion I: Some red are black → True (through grey→red chain)
Conclusion II: Some pink are black → True (follows from I since all red are pink)
For Data Sufficiency (3–5 questions): The key is to ask: “Can I answer the question uniquely with Statement I alone? Statement II alone? Both together?”
Don’t solve the problem — just check if it can be solved. That’s what data sufficiency tests.
What Toppers Do Differently in the Last 7 Days
Here’s the brutal truth: most students in the last week are busy feeling busy. They watch videos at 1.5x speed without pausing. They read notes without testing themselves. They confuse activity with progress.
Toppers do this instead:
Active recall over passive reading — close the book, write what you remember
Timer-based practice — every mock question gets 60–90 seconds max
Error log — one notebook page per topic, only for mistakes and patterns
Consistent sleep and exercise — non-negotiable; cognitive performance tanks without it
The MS Dhoni quote that sums it up perfectly: “Don’t think about the result when you’re in the process.” Your job for 7 days is to execute the plan. Trust the process.
Your TCS NQT Action Plan Starts Now
You don’t need more resources. You need to start.
Today:
Download the 7-day schedule
Bookmark the 8 YouTube resources listed above
Take a 20-question diagnostic mock in your weakest subject
This week:
Follow the day-wise plan without deviation
Do mock tests daily, not just on Day 7
Analyse every error — that’s where the real learning happens
The students who crack TCS NQT aren’t smarter than you. They’re more systematic. They started earlier, practised daily, and didn’t let anxiety turn into paralysis.
7 days. 8 resources. One plan.
Go crack it.
Ready to Go Faster? Here Are Your Options
The free playlist gets you far. But if you want mock tests, challenge questions, recorded sessions, and structured guidance — here’s what CampusMonk offers:
✅ Full Recording Access — watch anytime, anywhere
✅ Lakshya Mock Test Series included
✅ 21 Days Challenge with 500+ Questions
✅ Video explanations for all important topics
Start with the FREE playlist. If you want structured mock tests and guided questions, go for the ₹499 Lakshya Pack. If you want everything recorded and accessible anytime, the ₹799 program is the best value. Targeting TCS + other companies simultaneously? SANKALP is built for you.
The students who crack TCS NQT aren’t smarter than you. They’re more systematic. They started earlier, practised daily, and didn’t let anxiety become paralysis.
7 days. One plan. Your selection.
Go crack it.
TCS Digital & Prime Story Based Questions ! One Shot | All Previous Year Questions
Crack TCS 2026 with these Real PYQ coding questions — arrays, strings, logic, and more. Full explanations included. Bookmark this now.
Why These 20 Questions?
Every question here has appeared in TCS NQT drives between 2023–2025, sourced from real candidate reports and Campusmonk Final Strike sessions. Each includes a full problem statement, example, approach, Java solution, and complexity.
Q1. Best Time to Buy and Sell Stock
🟠 Medium | Arrays / Greedy
You are given an array prices[] where prices[i] is the stock price on day i. Choose one day to buy and a future day to sell. Return the maximum profit. Return 0 if no profit is possible.
Example
Input: prices = [7, 1, 5, 3, 6, 4] Output: 5 Buy on Day 2 (price=1), Sell on Day 5 (price=6). Profit = 5.
Input: prices = [7, 6, 4, 3, 1] Output: 0
Approach
Track the minimum price seen so far. At every index compute profit = price – minPrice. Update maxProfit. Single pass, no nested loops.
Solution
int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE, maxProfit = 0;
for (int price : prices) {
if (price < minPrice) minPrice = price;
else maxProfit = Math.max(maxProfit, price - minPrice);
}
return maxProfit;
}
Time: O(n) | Space: O(1)
Q2. Product of Array Except Self
🟠 Medium | Arrays / Prefix Product
Given nums[], return array answer[] where answer[i] equals the product of all elements except nums[i]. Must be O(n). Division is NOT allowed.
Example
Input: nums = [1, 2, 3, 4] Output: [24, 12, 8, 6]
Approach
Pass 1 left to right — fill result with left prefix products. Pass 2 right to left — multiply right suffix products using one running variable. No extra array needed.
Solution
int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
result[0] = 1;
for (int i = 1; i < n; i++)
result[i] = result[i-1] * nums[i-1];
int right = 1;
for (int i = n-1; i >= 0; i--) {
result[i] *= right;
right *= nums[i];
}
return result;
}
Time: O(n) | Space: O(1)
Q3. First Missing Positive
🔴 Hard | Arrays / Cyclic Sort
Given an unsorted integer array nums[], return the smallest missing positive integer. Must run in O(n) time and O(1) space.
Use the array itself as a hash map. Place each number x at index x-1 if it is in range [1, n]. Then scan — the first index where nums[i] does not equal i+1 gives the answer.
Solution
int firstMissingPositive(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
while (nums[i] > 0 && nums[i] <= n && nums[nums[i]-1] != nums[i]) {
int tmp = nums[nums[i]-1];
nums[nums[i]-1] = nums[i];
nums[i] = tmp;
}
}
for (int i = 0; i < n; i++)
if (nums[i] != i+1) return i+1;
return n+1;
}
Time: O(n) | Space: O(1)
Q4. Find the Duplicate Number
🟠 Medium-Hard | Floyd’s Cycle Detection
Array of n+1 integers, values in range [1, n], exactly one number repeats. Find it without modifying the array and using only O(1) extra space.
Treat the array as a linked list where index i points to nums[i]. A duplicate creates a cycle. Phase 1 — slow and fast pointers meet inside the cycle. Phase 2 — reset slow to start, advance both by one step until they meet. That meeting point is the duplicate.
Solution
int findDuplicate(int[] nums) {
int slow = nums[0], fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
Time: O(n) | Space: O(1)
Q5. Find All Duplicates in an Array
🟠 Medium | Index Marking
Given array of length n where all integers are in [1, n], each appearing once or twice. Return all integers that appear twice. O(n) time, O(1) space.
Example
Input: [4, 3, 2, 7, 8, 2, 3, 1] → Output: [2, 3]
Approach
For each number x, go to index abs(x)-1 and negate the value there. If it is already negative, abs(x) has appeared before and is a duplicate. The sign acts as a visited marker.
Solution
List<Integer> findDuplicates(int[] nums) {
List<Integer> result = new ArrayList<>();
for (int num : nums) {
int idx = Math.abs(num) - 1;
if (nums[idx] < 0) result.add(Math.abs(num));
else nums[idx] = -nums[idx];
}
return result;
}
Time: O(n) | Space: O(1)
Q6. Find Pivot Index
🟠 Medium | Arrays / Prefix Sum
Find the leftmost index where the sum of all elements to its left equals the sum of all elements to its right. Return -1 if none exists.
Example
Input: [1, 7, 3, 6, 5, 6] → Output: 3 Left sum = 1+7+3 = 11. Right sum = 5+6 = 11.
Approach
Compute total sum once. Walk left to right. At each index, rightSum = total – leftSum – nums[i]. If leftSum equals rightSum, return that index.
Solution
int pivotIndex(int[] nums) {
int total = 0;
for (int n : nums) total += n;
int leftSum = 0;
for (int i = 0; i < nums.length; i++) {
if (leftSum == total - leftSum - nums[i]) return i;
leftSum += nums[i];
}
return -1;
}
Time: O(n) | Space: O(1)
Q7. Pairs of Songs With Total Duration Divisible by 60
🟠 Medium | Hashing / Modular Arithmetic
Given song durations in seconds, return the count of pairs (i, j) where i < j and (time[i] + time[j]) % 60 == 0.
Example
Input: [30, 20, 150, 100, 40] → Output: 3 Pairs: (30,150)=180, (20,100)=120, (20,40)=60 — all divisible by 60.
Approach
This is Two Sum with mod 60. For each song, compute remainder = time % 60. The complement needed is (60 – remainder) % 60. Check how many previous songs have that complement remainder.
Solution
int numPairsDivisibleBy60(int[] time) {
int[] count = new int[60];
int pairs = 0;
for (int t : time) {
int rem = t % 60;
pairs += count[(60 - rem) % 60];
count[rem]++;
}
return pairs;
}
Time: O(n) | Space: O(1)
Q8. Partition Labels
🟠 Medium | Greedy / Strings
Partition string s into as many parts as possible so each letter appears in at most one part. Return a list of the sizes of each partition.
Record the last occurrence index of every character. Walk through the string expanding the current partition end whenever a character’s last occurrence is beyond the current end. When i equals end, the partition is complete.
Solution
List<Integer> partitionLabels(String s) {
int[] last = new int[26];
for (int i = 0; i < s.length(); i++)
last[s.charAt(i)-'a'] = i;
List<Integer> result = new ArrayList<>();
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
end = Math.max(end, last[s.charAt(i)-'a']);
if (i == end) { result.add(end-start+1); start = end+1; }
}
return result;
}
Time: O(n) | Space: O(1)
Q9. Minimum Steps to Make Two Strings Anagram II
🔴 Hard | Hashing / Strings
You can append any character to either string s or t in one step. Return the minimum number of steps to make s and t anagrams of each other.
Example
Input: s = “leetcode”, t = “coats” → Output: 7 Append “as” to s (2 steps) + append “leede” to t (5 steps) = 7.
Approach
Use one frequency array of size 26. Increment for every character in s, decrement for every character in t. Each entry now shows the imbalance for that character. Sum of all absolute values is the answer.
Solution
int minSteps(String s, String t) {
int[] freq = new int[26];
for (char c : s.toCharArray()) freq[c-'a']++;
for (char c : t.toCharArray()) freq[c-'a']--;
int steps = 0;
for (int f : freq) steps += Math.abs(f);
return steps;
}
Time: O(|s|+|t|) | Space: O(1)
Q10. Sort Characters by Frequency
🟠 Medium | Hashing / Bucket Sort
Given a string s, sort it in decreasing order based on character frequency.
Count character frequencies using a HashMap. Use bucket sort — create an array of lists indexed by frequency. Build the result string from the highest frequency bucket downward.
Solution
String frequencySort(String s) {
Map<Character,Integer> freq = new HashMap<>();
for (char c : s.toCharArray()) freq.put(c, freq.getOrDefault(c,0)+1);
List<Character>[] buckets = new List[s.length()+1];
for (char c : freq.keySet()) {
int f = freq.get(c);
if (buckets[f]==null) buckets[f]=new ArrayList<>();
buckets[f].add(c);
}
StringBuilder sb = new StringBuilder();
for (int i=s.length(); i>=1; i--)
if (buckets[i]!=null)
for (char c : buckets[i])
for (int j=0; j<i; j++) sb.append(c);
return sb.toString();
}
Time: O(n) | Space: O(n)
Q11. Insert Delete GetRandom O(1)
🔴 Hard | HashMap + ArrayList Design
Design RandomizedSet with insert(val), remove(val), and getRandom() — all running in average O(1) time.
Example
insert(1)→true, remove(2)→false, insert(2)→true getRandom()→1 or 2, remove(1)→true, getRandom()→2
Approach
HashMap stores value to index mapping. ArrayList stores all values. For O(1) delete, swap the target element with the last element, update the map for the swapped element, then remove the last. No shifting required.
Solution
class RandomizedSet {
Map<Integer,Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
Random rand = new Random();
boolean insert(int val) {
if (map.containsKey(val)) return false;
list.add(val); map.put(val, list.size()-1);
return true;
}
boolean remove(int val) {
if (!map.containsKey(val)) return false;
int idx=map.get(val), last=list.get(list.size()-1);
list.set(idx,last); map.put(last,idx);
list.remove(list.size()-1); map.remove(val);
return true;
}
int getRandom() { return list.get(rand.nextInt(list.size())); }
}
Time: O(1) avg all operations | Space: O(n)
Q12. Design Stack with Increment Operation
🔴 Hard | Stack / Lazy Propagation
Design CustomStack(maxSize) supporting push(x), pop() returning top or -1 if empty, and increment(k, val) adding val to bottom k elements. All operations must be O(1).
Use a lazy increment array inc[]. When increment(k, val) is called, store val at inc[min(k-1, top)] only — one operation, not k. When pop() is called, the element picks up its pending increment from inc[top] and passes it down to inc[top-1] before resetting.
Solution
class CustomStack {
int[] stack, inc; int top=-1, maxSize;
CustomStack(int maxSize) {
this.maxSize=maxSize; stack=new int[maxSize]; inc=new int[maxSize];
}
void push(int x) { if(top<maxSize-1) stack[++top]=x; }
int pop() {
if(top<0) return -1;
int val=stack[top]+inc[top];
if(top>0) inc[top-1]+=inc[top];
inc[top--]=0;
return val;
}
void increment(int k, int val) {
int idx=Math.min(k-1,top);
if(idx>=0) inc[idx]+=val;
}
}
Time: O(1) per operation | Space: O(maxSize)
Q13. Number of Recent Calls
🟠 Medium | Queue / Sliding Window
Implement RecentCounter where ping(t) records a request at time t and returns the count of requests in range [t-3000, t]. All calls have strictly increasing t.
Use a Queue. On each ping, add t to the queue. Remove all elements from the front that fall below t-3000. The queue size is the answer.
Solution
class RecentCounter {
Queue<Integer> q = new LinkedList<>();
int ping(int t) {
q.offer(t);
while (q.peek() < t-3000) q.poll();
return q.size();
}
}
Time: O(1) amortized | Space: O(1)
Q14. Maximum Sum of an Hourglass
🟠 Medium | 2D Arrays / Matrix Traversal
Given an m × n integer matrix grid, return the maximum sum of any hourglass shape. An hourglass is: top row of 3 + center element + bottom row of 3. It must be fully contained in the matrix.
Slide across every valid top-left position where i ≤ m-3 and j ≤ n-3. Compute the 7-element hourglass sum at each position and track the maximum.
Solution
int maxSum(int[][] grid) {
int m=grid.length, n=grid[0].length, max=Integer.MIN_VALUE;
for (int i=0; i<=m-3; i++)
for (int j=0; j<=n-3; j++) {
int sum = grid[i][j]+grid[i][j+1]+grid[i][j+2]
+ grid[i+1][j+1]
+ grid[i+2][j]+grid[i+2][j+1]+grid[i+2][j+2];
max = Math.max(max, sum);
}
return max;
}
Time: O(m×n) | Space: O(1)
Q15. Lucky Numbers in a Matrix
🟠 Medium | Matrix / Row-Column Analysis
Return all elements that are the minimum in their row and the maximum in their column.
Example
Input: [[3,7,8],[9,11,13],[15,16,17]] → Output: [15] 15 is the minimum of row 2 and the maximum of column 0.
Approach
Step 1 — collect all row minimums into a HashSet. Step 2 — for each column find the column maximum. If that maximum exists in the row-min set, it is a lucky number.
Solution
List<Integer> luckyNumbers(int[][] matrix) {
Set<Integer> rowMins = new HashSet<>();
for (int[] row : matrix) {
int mn=row[0]; for(int v:row) mn=Math.min(mn,v); rowMins.add(mn);
}
List<Integer> res = new ArrayList<>();
for (int j=0; j<matrix[0].length; j++) {
int mx=matrix[0][j];
for (int[] row:matrix) mx=Math.max(mx,row[j]);
if (rowMins.contains(mx)) res.add(mx);
}
return res;
}
Time: O(m×n) | Space: O(m)
Q16. Sort Students by Kth Score
🟠 Medium | Sorting / 2D Arrays
Given an m × n score matrix and integer k, sort the students (rows) in descending order by their score in the k-th exam column.
Use Arrays.sort with a custom comparator that compares row[k] in descending order. One line solution.
Solution
int[][] sortTheStudents(int[][] score, int k) {
Arrays.sort(score, (a, b) -> b[k] - a[k]);
return score;
}
Time: O(m log m) | Space: O(1)
Q17. Maximum XOR After Operations
🔴 Hard | Bit Manipulation
Given nums[], operation: nums[i] = nums[i] AND (nums[i] XOR x). This can only clear bits, never set new ones. Return the maximum possible XOR of all elements after any number of operations.
Example
Input: [3, 2, 4, 6] → Output: 7 Key insight: the operation can only remove bits. The maximum achievable XOR equals the bitwise OR of all elements.
Approach
Since no operation can ever introduce a new bit into any element, the maximum XOR of all elements is achieved when each bit that exists in any element is contributed independently. That is simply the OR of all elements.
Solution
int maximumXOR(int[] nums) {
int result = 0;
for (int num : nums) result |= num;
return result;
}
Time: O(n) | Space: O(1)
Q18. Minimum Operations to Reinitialize a Permutation
🔴 Hard | Math / Cycle Detection
Start with perm = [0, 1, 2, …, n-1] where n is even. Each operation: arr[i] = perm[i/2] if i is even, arr[i] = perm[n/2 + (i-1)/2] if i is odd. Return the minimum operations to return perm to its original state.
Example
n=4 → Output: 2 n=6 → Output: 4
Approach
Instead of simulating the full array at each step, just track where index 1 travels after each operation. All positions share the same cycle length. Count how many steps until index 1 returns to itself.
Solution
int reinitializePermutation(int n) {
int pos=1, steps=0;
do {
pos = (pos%2==0) ? pos/2 : n/2+(pos-1)/2;
steps++;
} while(pos!=1);
return steps;
}
Time: O(log n) | Space: O(1)
Q19. Check if Number is Sum of Powers of Three
🟠 Medium | Math / Number Theory
Return true if integer n can be represented as the sum of distinct powers of 3. Otherwise return false.
This is a base-3 representation check. Repeatedly divide n by 3. If any remainder is 2, that power of 3 would need to be used twice which violates the distinct condition. If all remainders are 0 or 1, return true.
Solution
boolean checkPowersOfThree(int n) {
while (n > 0) {
if (n % 3 == 2) return false;
n /= 3;
}
return true;
}
Time: O(log₃n) | Space: O(1)
Q20. Arithmetic Subarrays
🟠 Medium | Sorting / Query Processing
Given array nums[] and range queries defined by arrays l[] and r[], for each query check if subarray nums[l[i]..r[i]] can be rearranged into an arithmetic sequence. Return a list of boolean answers.
For each query extract the subarray, sort it, then check if all consecutive differences are equal. A valid arithmetic sequence has one uniform common difference throughout.
Solution
List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {
List<Boolean> res = new ArrayList<>();
for (int q=0; q<l.length; q++) {
int[] sub = Arrays.copyOfRange(nums, l[q], r[q]+1);
Arrays.sort(sub);
int diff=sub[1]-sub[0]; boolean ok=true;
for (int i=2;i<sub.length;i++)
if(sub[i]-sub[i-1]!=diff){ ok=false; break; }
res.add(ok);
}
return res;
}
Time: O(m × k log k) | Space: O(k)
4-Week Battle Plan
Week
Focus
Questions
Week 1
Arrays Deep Dive
Q1 → Q6
Week 2
Strings + Hashing
Q7 → Q10
Week 3
DS Design + Matrix
Q11 → Q16
Week 4
Math + Full Mock
Q17 → Q20
Pre-Exam Checklist
Can you solve Q3 (First Missing Positive) without notes?
Do you understand WHY Floyd’s Cycle works in Q4?
Can you explain Lazy Propagation in Q12 to someone?
Have you done 3 full timed mock sessions?
Have you written solutions by hand, not just typed them?
All five checked? You are ready.
Save this. Share it with your batch. One share could change someone’s career.
ACTUAL 100 TCS NQT CODING QUESTIONS (Ninja, Digital Prime)
Full Exam Format | Ninja | Digital | Prime | All Levels
LEVEL GUIDE — Know Your Tier
Tier
Round
Questions
Time
Difficulty
🟢 Ninja
Basic Coding
1–2 Qs
30 min
Easy
🔵 Digital
Advanced Coding
2–3 Qs
60 min
Medium–Hard
🔴 Prime
Expert Coding
3–4 Qs
90 min
Hard–Very Hard (DSA, DP, Graphs)
🟢 TCS NINJA — EASY LEVEL (Q1–Q35)
❓ Problem 1 — The Salary Table Printer
🏷️ Ninja | Number Logic | Easy
Problem Statement: Mike has started a new company and wants to print a salary table for his N employees. The salary of employee number i is computed as i × base_salary. The manager wants a neat table printed from employee 1 to N showing each employee’s number and their calculated salary.
Given N employees and a base salary B, print the salary of each employee from 1 to N.
Constraints:
1 ≤ N ≤ 100
1 ≤ B ≤ 10000
Input Format:
First line → Integer N
Second line → Integer B (base salary)
❓ Problem 2 — The Table Arrangement (Party Seating)
🏷️ Ninja | Math | Easy
Problem Statement: Mike has arranged a small party for the inauguration of his new startup. He has invited N employees indexed 1 to N. He wants to seat everyone at tables of size K (each table holds exactly K people). All employees must sit in index order continuously — employee 1 to K at table 1, K+1 to 2K at table 2, and so on. If the last table has fewer than K people, they still sit there.
Given N employees and table size K, print the table number for each employee.
Constraints:
1 ≤ N ≤ 1000
1 ≤ K ≤ N
Input Format:
First line → Integer N
Second line → Integer K
Output Format:
N lines in format: "Employee <i> → Table <table_number>"
❓ Problem 3 — The Cyclically Rotated Array (Clockwise, First Element Fixed)
🏷️ Ninja | Array | Easy ⭐ Frequently Repeated
Problem Statement: Given an array Arr[] of N integers and a positive integer K. The task is to cyclically rotate the array clockwise by K positions. Important: Keep the first element of the array unaltered — it stays at index 0. Only elements from index 1 to N-1 are rotated.
Constraints:
1 ≤ N ≤ 1000
1 ≤ K ≤ N
Input Format:
First line → Integer N
Second line → N space-separated integers
Third line → Integer K
Output Format:
N space-separated integers after rotation
Sample Input 1:
5
1 2 3 4 5
2
Sample Output 1:
1 4 5 2 3
Explanation: Original sub-array (index 1 to 4): 2 3 4 5 After clockwise rotation by 2: 4 5 2 3 First element stays: 1 Final: 1 4 5 2 3
❓ Problem 4 — The Mining Camp Number System
🏷️ Ninja | Number System | Easy
Problem Statement: Workers at a mining camp use octal numbers for their inventory system (base 8). A new computer system uses decimal. The camp manager must convert all old octal inventory codes to decimal for the new system.
Given an octal number (as a string), convert it to its decimal equivalent and print it.
Constraints:
Octal string length ≤ 10
String contains only digits 0-7
Problem Statement: A document printing company adds watermarks to every page. A watermark is a string W. The company receives a document string D and wants to check how many times the watermark W appears as a substring (overlapping also counts) in D.
Given strings D and W, count the total occurrences of W in D (including overlapping ones).
Constraints:
1 ≤ len(D) ≤ 10^5
1 ≤ len(W) ≤ len(D)
Both strings contain lowercase letters only
Input Format:
First line → String D (document)
Second line → String W (watermark)
Output Format:
Single integer → Count of occurrences (including overlapping)
Sample Input 1:
aaaa
aa
Sample Output 1:
3
Sample Input 2:
abcabcabc
abc
Sample Output 2:
3
Explanation:aa appears at positions 0, 1, 2 in aaaa → 3 times (overlapping counted).
❓ Problem 6 — The Sports Score Tracker
🏷️ Ninja | Conditional Logic | Easy
Problem Statement: In a school sports competition, teams earn points based on outcomes:
Win → +3 points
Draw → +1 point
Loss → 0 points
Given the results of N matches for a team (as W, D, or L), calculate their total points and determine their ranking category:
Points ≥ 20 → "Champion"
10 ≤ Points < 20 → "Qualifier"
Points < 10 → "Eliminated"
Constraints:
1 ≤ N ≤ 50
Each result is W, D, or L
Input Format:
First line → Integer N
Second line → N space-separated characters (W/D/L)
Output Format:
First line → "Total Points: X"
Second line → Category
Sample Input 1:
6
W W D L W W
Sample Output 1:
Total Points: 13
Qualifier
❓ Problem 7 — The Mixed Series Nth Term
🏷️ Ninja | Series | Easy ⭐ Most Repeated TCS Question
Problem Statement: During a science experiment, a researcher identified a special mixed series: 2, 1, 6, 2, 24, 6, 120, 24, 720, 120...
Given N (1-indexed position), find the Nth term of this series.
Constraints:
1 ≤ N ≤ 20
Input Format:
Single line → Integer N
Output Format:
Single integer → Nth term
Sample Input 1:
5
Sample Output 1:
24
Sample Input 2:
3
Sample Output 2:
6
❓ Problem 8 — The Digit Reversal Banking System
🏷️ Ninja | Number | Easy
Problem Statement: A banking system generates new account numbers by reversing the digits of a customer’s national ID and then checking if the reversed number is divisible by a given K. If divisible, the account is “Approved”, otherwise “Pending”.
Given an ID number N and a divisor K, reverse N and check divisibility.
Constraints:
1 ≤ N ≤ 10^9
1 ≤ K ≤ 100
Input Format:
First line → Integer N (national ID)
Second line → Integer K
Output Format:
First line → Reversed number
Second line → "Approved" or "Pending"
Problem Statement: A global weather station receives temperature readings in Celsius from field sensors. The international reporting system requires temperatures in both Fahrenheit and Kelvin.
Formulas:
Fahrenheit = (C × 9/5) + 32
Kelvin = C + 273.15
Given T temperatures in Celsius, print each converted to both Fahrenheit and Kelvin (rounded to 2 decimal places).
Constraints:
1 ≤ T ≤ 100
-273.15 ≤ C ≤ 1000
Input Format:
First line → Integer T
Next T lines → Temperature in Celsius (float)
Output Format:
T lines in format: "C°C = F°F = K K"
Sample Input 1:
2
0
100
Sample Output 1:
0°C = 32.00°F = 273.15 K
100°C = 212.00°F = 373.15 K
❓ Problem 10 — The Spy’s Caesar Cipher
🏷️ Ninja | String | Easy
Problem Statement: In World War II, spies encrypted messages using the Caesar Cipher — shifting every letter in the message by a fixed number K positions forward in the alphabet. Non-alphabet characters remain unchanged. The cipher is case-sensitive (lowercase stays lowercase, uppercase stays uppercase). Wrap around Z back to A.
Given a message string and shift value K, encode the message.
Constraints:
1 ≤ len(message) ≤ 10^4
0 ≤ K ≤ 25
Input Format:
First line → String (message)
Second line → Integer K (shift)
Output Format:
Single line → Encrypted message
Sample Input 1:
Hello World
3
Sample Output 1:
Khoor Zruog
Sample Input 2:
xyz
2
Sample Output 2:
zab
❓ Problem 11 — The Product of Non-Zero Elements
🏷️ Ninja | Array | Easy
Problem Statement: A factory quality control system stores component measurements in an array. Some measurements are recorded as 0 due to sensor failures and are invalid. The quality manager wants the product of all non-zero measurements to compute a quality index.
Given an array of N integers, compute and print the product of all non-zero elements. If all are zero, print 0.
Constraints:
1 ≤ N ≤ 100
0 ≤ arr[i] ≤ 1000
Input Format:
First line → Integer N
Second line → N space-separated integers
Output Format:
Single integer → Product of non-zero elements
Sample Input 1:
6
4 0 3 0 2 5
Sample Output 1:
120
Sample Input 2:
3
0 0 0
Sample Output 2:
0
❓ Problem 12 — The NGO Food Distribution
🏷️ Ninja | Math/Logic | Easy
Problem Statement: An NGO distributes food packets to poor children. They have F food packets and C children. They want to distribute packets equally and know how many packets each child gets and how many are leftover (remainder). If there are more packets than children, they distribute the rest to another village.
Given F packets and C children, find packets per child and leftovers.
Constraints:
1 ≤ F ≤ 10^9
1 ≤ C ≤ 10^6
Input Format:
First line → Integer F
Second line → Integer C
Output Format:
First line → "Each child gets: X packets"
Second line → "Leftover packets: Y"
Sample Input 1:
23
4
Sample Output 1:
Each child gets: 5 packets
Leftover packets: 3
❓ Problem 13 — The Train Schedule Conflict
🏷️ Ninja | Logic | Easy
Problem Statement: A railway system has N trains scheduled to depart. Each train has a departure time (in 24-hour format as integer, e.g., 1430 = 2:30 PM). Two trains have a conflict if they share the same departure time from the same platform. Given departure times of N trains, find how many unique departure times exist (to identify conflict-free slots).
Constraints:
1 ≤ N ≤ 1000
0 ≤ time ≤ 2359
Input Format:
First line → Integer N
Second line → N space-separated integers (departure times)
Output Format:
Single integer → Count of unique departure times
Sample Input 1:
6
900 1000 900 1430 1000 1200
Sample Output 1:
4
❓ Problem 14 — The Odd-Even Separator
🏷️ Ninja | Array | Easy
Problem Statement: A data analyst at a survey company received N responses (integers). She wants to separate the odd and even responses — print all even numbers first (in original order), then all odd numbers (in original order). This helps her categorize results faster.
Constraints:
1 ≤ N ≤ 10^5
1 ≤ arr[i] ≤ 10^6
Input Format:
First line → Integer N
Second line → N space-separated integers
Output Format:
First line → Even numbers space-separated
Second line → Odd numbers space-separated
(If no even/odd numbers, print "None" for that line)
Sample Input 1:
7
3 6 1 8 4 7 2
Sample Output 1:
6 8 4 2
3 1 7
❓ Problem 15 — The School Bell Pattern
🏷️ Ninja | Pattern | Easy
Problem Statement: A school bell rings in a pattern that can be represented as an inverted triangle of stars. For N rows, the first row has N stars, the second has N-1, and so on down to 1 star. The pattern is left-aligned.
Constraints:
1 ≤ N ≤ 50
Input Format:
Single line → Integer N
Output Format:
N rows of stars as described
Sample Input 1:
4
Sample Output 1:
* * * *
* * *
* *
*
❓ Problem 16 — The Maximum Repeat Character
🏷️ Ninja | String | Easy
Problem Statement: A cryptography professor analyzes letter frequency in ancient scripts to break codes. Given a string, she wants to find the character that appears the maximum number of times. If there’s a tie, return the character with the smaller ASCII value (alphabetically first).
Constraints:
1 ≤ len(S) ≤ 10^5
String contains only lowercase English letters
Input Format:
Single line → String S
Output Format:
Single character → Most frequent character
Sample Input 1:
aabbccddaaa
Sample Output 1:
a
Sample Input 2:
abcabc
Sample Output 2:
a
❓ Problem 17 — The Treasure Room Number
🏷️ Ninja | Math | Easy
Problem Statement: In an ancient palace, the treasure room number is calculated by finding the sum of all prime numbers between 1 and N (inclusive). A historian needs to compute this to decode an old map.
Given N, find the sum of all prime numbers from 1 to N.
Constraints:
1 ≤ N ≤ 10^6
Input Format:
Single line → Integer N
Output Format:
Single integer → Sum of all primes ≤ N
Sample Input 1:
10
Sample Output 1:
17
Explanation: Primes ≤ 10: 2, 3, 5, 7 → Sum = 17 ✅
❓ Problem 18 — The Assembly Line Counter
🏷️ Ninja | Array | Easy
Problem Statement: An electronics factory uses an assembly line where items are labelled with integers. The quality inspector wants to know the count of items whose value is greater than the average of all items on the line.
Given an array of N item values, count how many are strictly greater than the average.
Constraints:
1 ≤ N ≤ 10^5
1 ≤ arr[i] ≤ 10^6
Input Format:
First line → Integer N
Second line → N space-separated integers
Output Format:
Single integer → Count of items greater than average
Problem Statement: A puzzle book has a chapter on palindrome numbers. The puzzle asks: given a range [A, B], list all palindrome numbers in that range. A number is a palindrome if it reads the same forward and backward.
Constraints:
1 ≤ A ≤ B ≤ 10^6
Input Format:
First line → Integer A
Second line → Integer B
Output Format:
All palindrome numbers between A and B, space-separated.
If none exist, print "No Palindromes"
Sample Input 1:
10
30
Sample Output 1:
11 22
Sample Input 2:
100
110
Sample Output 2:
101
❓ Problem 20 — The Hexadecimal Mine Map
🏷️ Ninja | Number System | Easy
Problem Statement: Miners at a remote location use hexadecimal (base 16) maps. The surface team sends coordinates in decimal. The miners need to convert each decimal coordinate to its hexadecimal representation (uppercase letters A-F).
Given a decimal number N, convert it to hexadecimal.
Constraints:
0 ≤ N ≤ 10^9
Input Format:
Single line → Integer N
Output Format:
Uppercase hexadecimal string
Sample Input 1:
255
Sample Output 1:
FF
Sample Input 2:
16
Sample Output 2:
10
❓ Problem 21 — The Duplicate Removal Machine
🏷️ Ninja | String/Array | Easy
Problem Statement: A data cleaning company processes input strings. Their machine removes all duplicate characters from a string while preserving the order of first occurrence. The output is a string with each character appearing only once in the order they first appeared.
Constraints:
1 ≤ len(S) ≤ 10^5
String contains lowercase letters only
Input Format:
Single line → String S
Output Format:
Single line → String after removing duplicates
Sample Input 1:
programming
Sample Output 1:
progamin
Sample Input 2:
aabbccdd
Sample Output 2:
abcd
❓ Problem 22 — The Fibonacci Check at the Border
🏷️ Ninja | Number | Easy
Problem Statement: At an international border, a security system flags a traveller if their passport number is a Fibonacci number. The border officer receives a number N and must quickly determine: is it a Fibonacci number?
A Fibonacci number belongs to the sequence 0, 1, 1, 2, 3, 5, 8, 13…
Print "Fibonacci" or "Not Fibonacci".
Constraints:
0 ≤ N ≤ 10^15
Input Format:
Single line → Integer N
Output Format:
"Fibonacci" or "Not Fibonacci"
Sample Input 1:
13
Sample Output 1:
Fibonacci
Sample Input 2:
14
Sample Output 2:
Not Fibonacci
Hint: A number N is Fibonacci if and only if one or both of (5N²+4) or (5N²-4) is a perfect square.
❓ Problem 23 — The Space Colony Habitat Zones
🏷️ Ninja | Sorting | Easy
Problem Statement: NASA is planning a space colony. They have N habitat zones, each with a capacity value. The colony planner wants to assign zones in ascending order of capacity to smaller families first. Sort the zone capacities in ascending order and print them.
Use the Selection Sort algorithm (as specified by the colony’s legacy computer system).
Constraints:
1 ≤ N ≤ 1000
1 ≤ capacity[i] ≤ 10^6
Input Format:
First line → Integer N
Second line → N space-separated integers
Output Format:
N space-separated integers in ascending order
Sample Input 1:
5
64 25 12 22 11
Sample Output 1:
11 12 22 25 64
❓ Problem 24 — The Hospital Emergency Ward
🏷️ Ninja | Conditional | Easy
Problem Statement: A hospital emergency ward classifies patients based on their heart rate (BPM):
BPM < 60 → "Bradycardia" (too slow)
60 ≤ BPM ≤ 100 → "Normal"
BPM > 100 → "Tachycardia" (too fast)
Additionally, if the patient is above 60 years old and their BPM is outside 60–100, mark them as "High Risk" in addition to their condition.
Given age and BPM, classify the patient.
Constraints:
1 ≤ age ≤ 120
1 ≤ BPM ≤ 300
Input Format:
First line → Integer age
Second line → Integer BPM
Output Format:
Condition and risk level (if applicable)
Sample Input 1:
65
45
Sample Output 1:
Bradycardia
High Risk
Sample Input 2:
30
80
Sample Output 2:
Normal
❓ Problem 25 — The String Compression Challenge
🏷️ Ninja | String | Easy
Problem Statement: A communication system compresses strings by replacing consecutive repeated characters with the character followed by its count. For example, aaabbc becomes a3b2c1. If the compressed string is not shorter than the original, return the original string unchanged.
Constraints:
1 ≤ len(S) ≤ 10^5
String contains lowercase English letters
Input Format:
Single line → String S
Output Format:
Compressed string or original if compression is not beneficial
Problem Statement: A robot starts at position (0, 0) on an infinite grid. It receives a sequence of commands:
N → move 1 step North (y+1)
S → move 1 step South (y-1)
E → move 1 step East (x+1)
W → move 1 step West (x-1)
After executing all commands, print the final position of the robot, and whether it has returned to origin.
Constraints:
1 ≤ len(commands) ≤ 10^5
Input Format:
Single line → Command string (e.g., NESW)
Output Format:
First line → "Position: (x, y)"
Second line → "At Origin" or "Not At Origin"
Sample Input 1:
NESW
Sample Output 1:
Position: (0, 0)
At Origin
Sample Input 2:
NNN
Sample Output 2:
Position: (0, 3)
Not At Origin
❓ Problem 27 — The Canteen Bill Splitter
🏷️ Ninja | Math | Easy
Problem Statement: N friends go out for lunch at a canteen. The total bill is B rupees. They want to split it equally. However, the canteen uses a rule: each person pays the bill rounded up to the nearest integer (ceiling). Find the total amount collected and the extra amount collected over the original bill.
Constraints:
1 ≤ N ≤ 1000
1 ≤ B ≤ 10^6
Input Format:
First line → Integer N (friends)
Second line → Integer B (total bill)
Output Format:
First line → "Each pays: X"
Second line → "Total collected: Y"
Second line → "Extra: Z"
Sample Input 1:
3
100
Sample Output 1:
Each pays: 34
Total collected: 102
Extra: 2
❓ Problem 28 — The Star Diamond Pattern
🏷️ Ninja | Pattern | Easy
Problem Statement: A textile designer creates fabric patterns programmatically. She wants to print a diamond pattern made of stars for N rows (N is always odd). The top half expands from 1 to N stars, the bottom half contracts from N-2 to 1 star. Each row is center-aligned (padded with spaces).
Constraints:
1 ≤ N ≤ 19 (N is odd)
Input Format:
Single line → Odd integer N
Output Format:
Diamond pattern as described
Sample Input 1:
5
Sample Output 1:
*
***
*****
***
*
❓ Problem 29 — The Leap Year Festival Planner
🏷️ Ninja | Conditional Logic | Easy
Problem Statement: A cultural committee plans a special festival every leap year. They receive a list of years and must identify which ones are leap years to schedule the event.
A leap year is:
Divisible by 4
BUT if divisible by 100, it must ALSO be divisible by 400
Given N years, print each year and whether it is a "Leap Year" or "Not a Leap Year".
Constraints:
1 ≤ N ≤ 100
1000 ≤ year ≤ 9999
Input Format:
First line → Integer N
Next N lines → Year values
Output Format:
N lines: "YYYY: Leap Year" or "YYYY: Not a Leap Year"
Sample Input 1:
3
2000
1900
2024
Sample Output 1:
2000: Leap Year
1900: Not a Leap Year
2024: Leap Year
❓ Problem 30 — The Number Swap Without Temp Variable
🏷️ Ninja | Math/Bit | Easy
Problem Statement: Two engineers at a hardware company argue about the most efficient way to swap values of two variables without using a temporary variable. They want a program to swap two integers A and B using either arithmetic or XOR-based swapping and print the values before and after.
Constraints:
-10^9 ≤ A, B ≤ 10^9
Input Format:
First line → Integer A
Second line → Integer B
Output Format:
"Before: A=X B=Y"
"After: A=Y B=X"
Sample Input 1:
5
10
Sample Output 1:
Before: A=5 B=10
After: A=10 B=5
❓ Problem 31 — The Charity Odd Calculator
🏷️ Ninja | Series | Easy
Problem Statement: A charity organization donates money based on odd numbers. They donate to the Nth odd number in the sequence 1, 3, 5, 7, 9… The charity manager also wants the sum of first N odd numbers (which is always N²).
Given N, print the Nth odd number and the sum of the first N odd numbers.
Constraints:
1 ≤ N ≤ 10^6
Input Format:
Single line → Integer N
Output Format:
First line → "Nth Odd: X"
Second line → "Sum of first N odds: Y"
Sample Input 1:
5
Sample Output 1:
Nth Odd: 9
Sum of first N odds: 25
❓ Problem 32 — The String Rotation Check
🏷️ Ninja | String | Easy
Problem Statement: Two scientists are exchanging planetary coordinates encoded as strings. They discovered that their communication system sometimes rotates the string (circular shift). Given two strings S1 and S2, determine if S2 is a rotation of S1.
A rotation of abcd can be bcda, cdab, dabc, etc.
Print "Rotation" or "Not Rotation".
Constraints:
1 ≤ len(S1), len(S2) ≤ 10^5
Input Format:
First line → String S1
Second line → String S2
Output Format:
"Rotation" or "Not Rotation"
Sample Input 1:
abcd
cdab
Sample Output 1:
Rotation
Sample Input 2:
hello
lloeh
Sample Output 2:
Not Rotation
❓ Problem 33 — The Capital Letters Counter
🏷️ Ninja | String | Easy
Problem Statement: A proofreading software checks business letters for formatting. One rule is: capital letters should not be overused. The software counts the number of uppercase letters and if they are more than 40% of total alphabets, it prints a “Format Warning”, otherwise "Format OK".
Constraints:
1 ≤ len(S) ≤ 10^5
Input Format:
Single line → String S
Output Format:
First line → "Uppercase: X, Total Alphabets: Y"
Second line → "Format Warning" or "Format OK"
Sample Input 1:
Hello WORLD how Are you
Sample Output 1:
Uppercase: 8, Total Alphabets: 17
Format Warning
❓ Problem 34 — The Number Classification Machine
🏷️ Ninja | Number Theory | Easy
Problem Statement: A number classification machine at a research center classifies each number it receives as one of the following:
Positive Even → "PE"
Positive Odd → "PO"
Negative Even → "NE"
Negative Odd → "NO"
Zero → "Z"
Given T numbers, classify each one.
Constraints:
1 ≤ T ≤ 100
-10^6 ≤ num ≤ 10^6
Input Format:
First line → Integer T
Next T lines → Each number
Output Format:
T lines → Classification code for each number
Sample Input 1:
5
4
-3
0
-8
7
Sample Output 1:
PE
NO
Z
NE
PO
❓ Problem 35 — The Area Calculator Kiosk
🏷️ Ninja | Math | Easy
Problem Statement: A construction kiosk allows workers to calculate the area of various shapes. Given a shape type and its dimensions, compute the area (round to 2 decimal places):
circle R → Area = π × R²
rectangle L W → Area = L × W
triangle B H → Area = 0.5 × B × H
Use π = 3.14159265
Constraints:
Shape is one of: circle, rectangle, triangle
All dimensions are positive integers ≤ 10^4
Input Format:
First line → Shape name
Next line → Dimensions (1 or 2 integers based on shape)
Output Format:
"Area: X.XX"
Sample Input 1:
circle
7
Sample Output 1:
Area: 153.94
Sample Input 2:
triangle
10 5
Sample Output 2:
Area: 25.00
🔵 TCS DIGITAL — MEDIUM–HARD LEVEL (Q36–Q70)
❓ Problem 36 — The Linked List Reversal Engine
🏷️ Digital | Linked List | Medium
Problem Statement: A data processing system stores a sequence of transaction amounts as a singly linked list. The system needs to reverse the order of transactions for end-of-day reconciliation. Write a program to reverse a singly linked list and print the reversed sequence.
The linked list is given as an array of N values; build the linked list internally, reverse it using pointer manipulation (not by just reversing the array), and print the result.
Constraints:
1 ≤ N ≤ 10^5
1 ≤ val[i] ≤ 10^6
Input Format:
First line → Integer N
Second line → N space-separated integers (linked list values head to tail)
Output Format:
N space-separated integers (reversed linked list)
Sample Input 1:
5
1 2 3 4 5
Sample Output 1:
5 4 3 2 1
Sample Input 2:
1
42
Sample Output 2:
42
❓ Problem 37 — The Balanced Bracket Security Check
🏷️ Digital | Stack | Medium ⭐ Repeatedly Asked
Problem Statement: A software security tool validates code syntax. One check is to verify that all brackets are balanced. A string with brackets (, ), {, }, [, ] is balanced if:
Every opening bracket has a corresponding closing bracket.
Brackets are closed in the correct order.
Empty string is considered balanced.
Given a string, determine if brackets are balanced. Print "Balanced" or "Not Balanced".
Constraints:
0 ≤ len(S) ≤ 10^5
String contains only bracket characters
Input Format:
Single line → Bracket string
Output Format:
"Balanced" or "Not Balanced"
Sample Input 1:
{[()]}
Sample Output 1:
Balanced
Sample Input 2:
{[(])}
Sample Output 2:
Not Balanced
❓ Problem 38 — The Wildcard Pattern Matcher
🏷️ Digital | String/DP | Medium ⭐ Actual TCS Repeated
Problem Statement: A text search engine allows wildcard pattern matching. The wildcard character ? matches exactly one character, and * matches any sequence of characters (including empty). Given a text string T and a pattern string P, check if P matches T completely.
Print "Match" or "No Match".
Constraints:
1 ≤ len(T) ≤ 1000
1 ≤ len(P) ≤ 1000
Input Format:
First line → Text string T
Second line → Pattern string P
Output Format:
"Match" or "No Match"
Sample Input 1:
aab
*b
Sample Output 1:
Match
Sample Input 2:
hello
he?lo
Sample Output 2:
Match
Sample Input 3:
hello
h*rld
Sample Output 3:
No Match
❓ Problem 39 — The Inventory Merge Sort
🏷️ Digital | Sorting | Medium
Problem Statement: A large e-commerce company has two sorted inventory lists from two different warehouses, each sorted in ascending order by product ID. The central system needs to merge them into one sorted list efficiently (Merge Sort merge step — O(n+m) time) for unified inventory management.
Constraints:
1 ≤ N, M ≤ 10^5
1 ≤ product_id ≤ 10^9
Input Format:
First line → Integer N (size of list 1)
Second line → N space-separated integers (sorted)
Third line → Integer M (size of list 2)
Fourth line → M space-separated integers (sorted)
Output Format:
(N+M) space-separated integers in sorted ascending order
Sample Input 1:
4
1 3 5 7
4
2 4 6 8
Sample Output 1:
1 2 3 4 5 6 7 8
❓ Problem 40 — The Network Queue Simulation
🏷️ Digital | Queue/Stack | Medium
Problem Statement: A network router processes data packets using a queue (FIFO). The system receives a sequence of operations:
ENQUEUE X → Add packet with value X to the queue
DEQUEUE → Remove and print the front packet
PEEK → Print the front without removing
SIZE → Print current size of queue
ISEMPTY → Print "Empty" or "Not Empty"
Simulate the queue operations and produce the output.
Constraints:
1 ≤ operations ≤ 10^4
1 ≤ X ≤ 10^6
No DEQUEUE/PEEK on empty queue
Input Format:
First line → Integer Q (number of operations)
Next Q lines → Each operation
Output Format:
Output for DEQUEUE, PEEK, SIZE, ISEMPTY operations (one per line)
Sample Input 1:
6
ENQUEUE 10
ENQUEUE 20
PEEK
DEQUEUE
SIZE
ISEMPTY
Sample Output 1:
10
10
1
Not Empty
❓ Problem 41 — The Hospital Appointment BFS Scheduler
🏷️ Digital | Graph/BFS | Medium
Problem Statement: A large hospital has departments connected by corridors. Given a graph of department connections, a patient starts at department 1 and wants to visit all reachable departments using BFS (shortest hop-count order). Print the BFS traversal order starting from node 1.
Constraints:
1 ≤ N ≤ 100 (departments)
0 ≤ E ≤ N*(N-1)/2 (corridors, undirected)
Graph may not be fully connected
Input Format:
First line → Two integers N E
Next E lines → Two integers U V (undirected edge)
Output Format:
BFS traversal order starting from node 1, space-separated
Sample Input 1:
6 5
1 2
1 3
2 4
3 5
4 6
Sample Output 1:
1 2 3 4 5 6
❓ Problem 42 — The IT Department Binary Tree Level Order
🏷️ Digital | Tree/BFS | Medium
Problem Statement: An IT department stores employee hierarchy as a binary tree, where the root is the CEO. The HR team needs a level-order traversal (BFS) of this tree to generate a company org-chart floor-by-floor.
Given a binary tree via array representation (1-indexed, left child = 2i, right child = 2i+1, -1 means null), print the level-order traversal.
Constraints:
1 ≤ N ≤ 10^3
-1 represents null node
Input Format:
First line → Integer N (number of nodes in array)
Second line → N space-separated integers (tree array, -1 = null)
Problem Statement: A cashier at a store wants to give back change of amount A using the minimum number of coins. The store has infinite supply of coins of given denominations. If it is not possible to make exact change, print -1.
Constraints:
1 ≤ number of denominations ≤ 20
1 ≤ denomination[i] ≤ 1000
1 ≤ A ≤ 10^4
Input Format:
First line → Integer N (number of denominations)
Second line → N space-separated coin values
Third line → Integer A (amount)
Output Format:
Single integer → Minimum coins needed, or -1 if impossible
Problem Statement: A drone delivery company maps delivery zones as a directed graph. The central hub (node 1) needs to reach all delivery zones. Using DFS, determine the order drones would explore each zone. Also check if all zones are reachable from node 1; if not, print the unreachable zones.
Constraints:
1 ≤ N ≤ 100
0 ≤ E ≤ N*(N-1)
Directed graph
Input Format:
First line → Two integers N E
Next E lines → Two integers U V (directed edge U → V)
Output Format:
First line → "DFS: " followed by DFS order space-separated
Second line → "Unreachable: " followed by unreachable nodes, or "All Reachable"
Sample Input 1:
5 4
1 2
1 3
2 4
3 5
Sample Output 1:
DFS: 1 2 4 3 5
All Reachable
❓ Problem 45 — The Longest Common Subsequence Archive
🏷️ Digital | DP | Medium–Hard
Problem Statement: Two historians are analyzing ancient texts. They want to find the Longest Common Subsequence (LCS) between two texts (strings) — the longest sequence of characters that appears in both strings in the same order (not necessarily contiguous).
Given two strings, print the length of their LCS.
Constraints:
1 ≤ len(S1) ≤ 1000
1 ≤ len(S2) ≤ 1000
Input Format:
First line → String S1
Second line → String S2
Output Format:
Single integer → Length of LCS
Sample Input 1:
ABCBDAB
BDCABA
Sample Output 1:
4
Explanation: LCS is BCBA or BDAB, length = 4 ✅
❓ Problem 46 — The Matrix Diagonal Sum
🏷️ Digital | Matrix | Medium
Problem Statement: A data analyst is studying a square matrix of N×N values. She wants to find the sum of both diagonals (primary and secondary), but if N is odd, the center element should be counted only once (not twice).
Constraints:
1 ≤ N ≤ 100
1 ≤ matrix[i][j] ≤ 10^6
Input Format:
First line → Integer N
Next N lines → N space-separated integers per row
Output Format:
Single integer → Sum of both diagonals (center counted once)
Problem Statement: A video game character is positioned at index 0 of an array. Each element represents the maximum jump length from that position. The character wants to reach the last index. Determine if it is possible to reach the last index.
Print "Can Reach" or "Cannot Reach".
Constraints:
1 ≤ N ≤ 10^4
0 ≤ arr[i] ≤ 10^4
Input Format:
First line → Integer N
Second line → N space-separated integers
Output Format:
"Can Reach" or "Cannot Reach"
Sample Input 1:
6
2 3 1 1 4 0
Sample Output 1:
Can Reach
Sample Input 2:
6
3 2 1 0 4 0
Sample Output 2:
Cannot Reach
❓ Problem 48 — The Student Distribution Problem (Combinatorics)
🏷️ Digital | Math/Combinatorics | Hard
Problem Statement: A teacher wants to distribute N students equally into R classrooms. The number of ways to arrange students in classrooms (where arrangement within classroom matters) is calculated using a multinomial coefficient. Compute the number of ways modulo 10^9+7.
Given R rooms and N students, find the count of arrangements where students are distributed as equally as possible (some rooms get floor(N/R) students, others get ceil(N/R)).
Constraints:
1 ≤ R ≤ N ≤ 10^6
Input Format:
First line → Integer T (test cases)
Next T lines → Two integers R N
Output Format:
T lines → Answer for each test case modulo 10^9+7
Sample Input 1:
2
3 6
2 5
Sample Output 1:
90
20
❓ Problem 49 — The Smart City Traffic Signal
🏷️ Digital | Graph/Shortest Path | Medium–Hard
Problem Statement: A smart city has N intersections and M roads. Each road has a travel time (weight). An ambulance at intersection S needs the shortest time to reach the hospital at intersection D (Dijkstra’s Algorithm).
Constraints:
1 ≤ N ≤ 1000
1 ≤ M ≤ 10^4
1 ≤ weight ≤ 10^4
1 ≤ S, D ≤ N
Input Format:
First line → Two integers N M
Next M lines → Three integers U V W (edge from U to V with weight W, undirected)
Last line → Two integers S D
Output Format:
Single integer → Shortest time from S to D, or -1 if unreachable
Problem Statement: A linguistics researcher has a list of N words. She wants to group all anagrams together and print each group on a separate line (words within a group separated by spaces, groups in order of first occurrence).
Constraints:
1 ≤ N ≤ 10^4
1 ≤ len(word) ≤ 100
Words are lowercase
Input Format:
First line → Integer N
Second line → N space-separated words
Output Format:
Each group of anagrams on a separate line
Sample Input 1:
6
eat tea tan ate nat bat
Sample Output 1:
eat tea ate
tan nat
bat
❓ Problem 51 — The Rectangle Overlap Detector
🏷️ Digital | Geometry | Medium
Problem Statement: A GIS software system detects if two land plots (rectangles) overlap. Each rectangle is defined by its bottom-left (x1, y1) and top-right (x2, y2) coordinates. Two rectangles overlap if their intersection has positive area (touching at boundary only is NOT overlap).
Print "Overlap" or "No Overlap".
Constraints:
-10^4 ≤ coordinates ≤ 10^4
Input Format:
First line → x1 y1 x2 y2 (Rectangle 1)
Second line → x3 y3 x4 y4 (Rectangle 2)
Output Format:
"Overlap" or "No Overlap"
Sample Input 1:
0 0 4 4
2 2 6 6
Sample Output 1:
Overlap
Sample Input 2:
0 0 2 2
3 3 5 5
Sample Output 2:
No Overlap
❓ Problem 52 — The Word Ladder Distance
🏷️ Digital | BFS/Graph | Hard
Problem Statement: In a word transformation game, a player must transform word BEGIN to word TARGET by changing exactly one letter at a time, where each intermediate word must exist in a given dictionary. Find the minimum number of steps (transformations) needed. If impossible, print 0.
Constraints:
2 ≤ word length ≤ 5 (all words same length)
1 ≤ dictionary size ≤ 500
Input Format:
First line → String BEGIN
Second line → String TARGET
Third line → Integer N (dictionary size)
Next N lines → Dictionary words (one per line)
Output Format:
Single integer → Minimum transformations (or 0 if impossible)
Sample Input 1:
hit
cog
6
hot
dot
dog
lot
log
cog
Sample Output 1:
5
Explanation: hit → hot → dot → dog → cog (5 steps) ✅
❓ Problem 53 — The Largest Rectangle in Histogram
🏷️ Digital | Stack | Hard
Problem Statement: An architect is analyzing a city skyline represented as a histogram (bar chart) where each bar has width 1 and a given height. She wants to find the area of the largest rectangle that can be formed within the histogram bars.
Constraints:
1 ≤ N ≤ 10^5
0 ≤ height[i] ≤ 10^4
Input Format:
First line → Integer N
Second line → N space-separated integers (bar heights)
Output Format:
Single integer → Maximum rectangle area
Sample Input 1:
6
2 1 5 6 2 3
Sample Output 1:
10
Explanation: Bars of height 5 and 6 form a rectangle of area 10 ✅
❓ Problem 54 — The Network Infection Spread (BFS Levels)
🏷️ Digital | BFS/Graph | Medium
Problem Statement: A cybersecurity analyst is simulating a virus spread through N computers (nodes 1 to N) connected by a network graph. The virus starts at node 1 at time 0. Every second, it infects all directly connected uninfected computers simultaneously. Find the time taken to infect all computers, and if any computer is unreachable, print its list.
Constraints:
1 ≤ N ≤ 1000
Undirected graph
Input Format:
First line → Two integers N E
Next E lines → Two integers U V (undirected edge)
Output Format:
First line → "Infection Time: T seconds"
Second line → "Unreachable: X Y Z" or "All Infected"
Sample Input 1:
5 4
1 2
1 3
2 4
3 5
Sample Output 1:
Infection Time: 2 seconds
All Infected
❓ Problem 55 — The Maximum Path Sum in Binary Tree
🏷️ Digital | Tree/DFS | Hard
Problem Statement: A financial planning company represents investment plans as a binary tree where each node holds a profit/loss value (can be negative). An analyst wants to find the maximum path sum — the maximum sum achievable along any path from any node to any node (path must go through connected nodes, can start/end anywhere).
Constraints:
1 ≤ N ≤ 10^4
-10^4 ≤ node_val ≤ 10^4
Input Format:
First line → Integer N
Second line → N space-separated integers (tree in level-order, -1 = null)
Output Format:
Single integer → Maximum path sum
Sample Input 1:
5
-10 9 20 -1 -1 15 7
Sample Output 1:
42
Explanation: Path: 15 → 20 → 7 = 42 ✅
❓ Problem 56 — The Minimum Spanning Tree Cost
🏷️ Digital | Graph/MST | Hard
Problem Statement: A telecom company wants to lay fibre cables connecting N cities with minimum total cable length. Given the cost of laying cable between each pair of cities, find the Minimum Spanning Tree cost using Kruskal’s or Prim’s algorithm.
Constraints:
2 ≤ N ≤ 500
Weighted undirected connected graph
Input Format:
First line → Two integers N E
Next E lines → Three integers U V W (edge with weight)
Problem Statement: A data encoding system partitions a string into substrings where every substring is a palindrome. The system wants to know the minimum number of cuts needed to partition a given string S such that every resulting substring is a palindrome.
Problem Statement: A university curriculum has N courses. Some courses have prerequisites. Given a list of prerequisite pairs (A, B meaning A must be taken before B), produce a valid course order using Topological Sort. If there’s a cycle (impossible to complete all courses), print "Impossible".
Constraints:
1 ≤ N ≤ 100
Directed acyclic graph (or cyclic — candidate must detect)
Input Format:
First line → Two integers N E
Next E lines → Two integers A B (A is prerequisite of B)
Output Format:
Space-separated topological order, or "Impossible"
Sample Input 1:
4 3
1 2
1 3
3 4
Sample Output 1:
1 3 4 2
(Any valid topological order is accepted)
❓ Problem 59 — The Flood Fill Algorithm
🏷️ Digital | Graph/DFS | Medium
Problem Statement: A paint application has a canvas represented as an N×M grid of integers (colors). A user clicks on cell (SR, SC) and selects a new color NC. The flood fill operation changes the color of the clicked cell and all adjacent (4-directional) cells with the same original color to the new color — recursively.
Print the grid after flood fill.
Constraints:
1 ≤ N, M ≤ 50
0 ≤ color ≤ 100
Input Format:
First line → Two integers N M
Next N lines → M space-separated integers (grid)
Next line → Three integers SR SC NC
Output Format:
N lines of M space-separated integers (modified grid)
Sample Input 1:
3 3
1 1 1
1 1 0
1 0 0
1 1 2
Sample Output 1:
2 2 2
2 2 0
2 0 0
❓ Problem 60 — The Sliding Window Maximum
🏷️ Digital | Deque | Hard
Problem Statement: A financial analyst tracks stock prices over N days. She uses a sliding window of size K to find the maximum price in each window as it moves from left to right across the data. Efficient O(n) solution is expected (use deque).
Constraints:
1 ≤ K ≤ N ≤ 10^5
1 ≤ price[i] ≤ 10^6
Input Format:
First line → Two integers N K
Second line → N space-separated integers (prices)
Output Format:
(N-K+1) space-separated integers → Max of each window
Sample Input 1:
8 3
1 3 -1 -3 5 3 6 7
Sample Output 1:
3 3 5 5 6 7
❓ Problem 61 — The Matrix Chain Multiplication Order
🏷️ Digital | DP | Hard
Problem Statement: A computer graphics system needs to multiply a chain of N matrices. The order of multiplication affects the total number of scalar multiplications needed. Given the dimensions of N matrices (as an array where matrix i has dimensions arr[i-1] × arr[i]), find the minimum number of scalar multiplications needed.
Constraints:
2 ≤ N ≤ 100
1 ≤ arr[i] ≤ 100
Input Format:
First line → Integer N (number of matrices)
Second line → (N+1) space-separated integers (dimension array)
Output Format:
Single integer → Minimum scalar multiplications
Sample Input 1:
3
40 20 30 10
Sample Output 1:
26000
❓ Problem 62 — The Rat in a Maze Pathfinder
🏷️ Digital | Backtracking | Medium–Hard
Problem Statement: A lab rat starts at the top-left corner of an N×N maze (cell 0,0) and needs to reach the bottom-right corner (N-1, N-1). The maze is represented as a 2D grid where 1 = open path and 0 = wall. The rat can move Down (D) or Right (R) only. Print all valid paths in lexicographic order. If no path exists, print "No Path".
Constraints:
2 ≤ N ≤ 10
maze[i][j] ∈ {0, 1}
Input Format:
First line → Integer N
Next N lines → N space-separated integers (maze row)
Output Format:
All valid paths as strings of D/R characters, one per line
Sample Input 1:
4
1 0 0 0
1 1 0 1
1 1 0 0
0 1 1 1
Sample Output 1:
DDRDRR
DDRRD
(exact output depends on direction rules — candidates compute)
❓ Problem 63 — The N-Queen Placement
🏷️ Digital | Backtracking | Hard
Problem Statement: The classic N-Queens problem: Place N queens on an N×N chessboard such that no two queens attack each other (no two in same row, column, or diagonal). Print the total number of distinct solutions.
Constraints:
1 ≤ N ≤ 12
Input Format:
Single line → Integer N
Output Format:
Single integer → Number of distinct solutions
Sample Input 1:
4
Sample Output 1:
2
Sample Input 2:
8
Sample Output 2:
92
❓ Problem 64 — The Trie-Based Autocomplete
🏷️ Digital | Trie | Hard
Problem Statement: A search engine builds an autocomplete system using a Trie data structure. Given a dictionary of N words, and Q prefix queries, for each query print all words in the dictionary that start with that prefix. If no words match, print "No Suggestions". Words should be printed in lexicographic order.
Constraints:
1 ≤ N ≤ 1000
1 ≤ Q ≤ 100
All strings contain lowercase letters
Input Format:
First line → Integer N
Next N lines → Dictionary words
Next line → Integer Q
Next Q lines → Prefix queries
Output Format:
For each query: matching words comma-separated, or "No Suggestions"
Sample Input 1:
5
apple
app
application
apt
bat
2
app
ba
Sample Output 1:
app,apple,application
bat
❓ Problem 65 — The Subarray Product Less Than K
🏷️ Digital | Sliding Window | Medium
Problem Statement: A factory’s production line records daily output. A quality supervisor wants to know how many contiguous subarrays have a product strictly less than K. Each element is a positive integer.
Constraints:
1 ≤ N ≤ 3 × 10^4
1 ≤ arr[i] ≤ 1000
0 < K ≤ 10^6
Input Format:
First line → Two integers N K
Second line → N space-separated positive integers
Output Format:
Single integer → Count of subarrays with product < K
Sample Input 1:
4 100
10 5 2 6
Sample Output 1:
8
❓ Problem 66 — The Serialize and Deserialize Binary Tree
🏷️ Digital | Tree | Hard
Problem Statement: A cloud backup system serializes binary trees to strings for storage and deserializes them back. Serialize a binary tree to a comma-separated string (use "null" for missing nodes, level-order). Then deserialize back and print in-order traversal to verify correctness.
Constraints:
0 ≤ N ≤ 100 nodes
-1000 ≤ node_val ≤ 1000
Input Format:
First line → Comma-separated serialized tree (level-order, "null" for empty)
Output Format:
First line → Serialized string (as-is)
Second line → In-order traversal of deserialized tree
Sample Input 1:
1,2,3,null,null,4,5
Sample Output 1:
1,2,3,null,null,4,5
2 1 4 3 5
❓ Problem 67 — The Prison Break Grid
🏷️ Digital | BFS/Grid | Medium
Problem Statement: A prisoner is trapped in an N×M grid cell (SR, SC) and needs to reach the exit at (ER, EC). The grid has walls (#) and open cells (.). The prisoner can move in 4 directions (Up, Down, Left, Right). Find the minimum steps to escape, or print -1 if impossible.
Constraints:
1 ≤ N, M ≤ 200
Input Format:
First line → Two integers N M
Next N lines → Grid rows (each character is . or #)
Next line → SR SC ER EC (start and end positions, 0-indexed)
Problem Statement: Scientists discover an alien civilization’s dictionary. The dictionary is sorted in the alien language’s own alphabetical order. Given a sorted list of alien words, deduce the order of letters in the alien alphabet (topological sort on characters). If the order is ambiguous, output any valid order. If it is impossible (cycle), print "Invalid Dictionary".
Constraints:
2 ≤ N ≤ 100 words
All characters are lowercase English letters
Input Format:
First line → Integer N
Next N lines → Alien words in sorted order
Output Format:
String → Deduced letter ordering, or "Invalid Dictionary"
Sample Input 1:
4
baa
abcd
abca
cab
Sample Output 1:
bdac
(Any valid topological order)
❓ Problem 69 — The Sudoku Validator
🏷️ Digital | Matrix/Logic | Medium
Problem Statement: A puzzle verification system checks submitted 9×9 Sudoku boards. A filled Sudoku board is valid if:
Each row contains digits 1–9 with no repetition
Each column contains digits 1–9 with no repetition
Each of the 9 3×3 sub-boxes contains digits 1–9 with no repetition
Print "Valid Sudoku" or "Invalid Sudoku".
Constraints:
Exactly 9 rows and 9 columns
All values are integers 1–9
Problem Statement: A thief is robbing a jewellery shop and can carry a bag of maximum weight capacity W. There are N items, each with a weight and a value. The thief wants to maximize the total value without exceeding W. Items cannot be split (0/1 Knapsack).
Constraints:
1 ≤ N ≤ 100
1 ≤ W ≤ 1000
1 ≤ weight[i] ≤ W
1 ≤ value[i] ≤ 10^4
Input Format:
First line → Two integers N W
Next N lines → Two integers weight value
Output Format:
Single integer → Maximum value achievable
Sample Input 1:
4 7
1 1
3 4
4 5
5 7
Sample Output 1:
9
🔴 TCS PRIME — EXPERT LEVEL (Q71–Q100)
❓ Problem 71 — The Alien Invasion Segment Tree
🏷️ Prime | Segment Tree | Very Hard
Problem Statement: An alien tracking system monitors N radar readings. It supports two operations repeatedly in real-time:
UPDATE i x → Update the reading at position i to x
QUERY l r → Find the maximum reading in range [l, r]
Use a Segment Tree to handle both operations in O(log n).
Constraints:
1 ≤ N ≤ 10^5
1 ≤ Q ≤ 10^5
1 ≤ i, l, r ≤ N
1 ≤ x ≤ 10^9
Input Format:
First line → Two integers N Q
Second line → N space-separated integers (initial readings)
Next Q lines → "UPDATE i x" or "QUERY l r"
Output Format:
For each QUERY, print the maximum value on a new line
Problem Statement: A financial system tracks N accounts with initial balances. It processes:
ADD i x → Add x to account i
SUM l r → Print total balance from account l to r
Use a Binary Indexed Tree (Fenwick Tree) for O(log n) per operation.
Constraints:
1 ≤ N ≤ 10^6
1 ≤ Q ≤ 10^6
Input Format:
First line → Two integers N Q
Second line → N initial balances
Next Q lines → "ADD i x" or "SUM l r"
Output Format:
Answer for each SUM query on a new line
Sample Input 1:
5 3
1 2 3 4 5
SUM 1 3
ADD 2 5
SUM 1 3
Sample Output 1:
6
11
❓ Problem 73 — The Interstellar LRU Cache
🏷️ Prime | HashMap + Doubly Linked List | Very Hard
Problem Statement: A space station computer uses an LRU (Least Recently Used) cache of capacity C. It processes GET and PUT operations:
GET key → Return value if exists, else return -1. Mark as recently used.
PUT key value → Insert or update. If capacity exceeded, evict least recently used.
Implement the LRU cache and simulate all operations.
Constraints:
1 ≤ C ≤ 3000
1 ≤ operations ≤ 2 × 10^4
Input Format:
First line → Two integers C Q
Next Q lines → "GET key" or "PUT key value"
Output Format:
For each GET, print the value or -1
Sample Input 1:
2 7
PUT 1 1
PUT 2 2
GET 1
PUT 3 3
GET 2
PUT 4 4
GET 1
Sample Output 1:
1
-1
1
❓ Problem 74 — The Maximum Flow Water Distribution
🏷️ Prime | Graph/Max Flow | Very Hard
Problem Statement: A city engineer is designing a water distribution network modelled as a directed graph with N nodes. Each edge has a maximum flow capacity. Find the maximum water flow from source (node 1) to sink (node N) using the Ford-Fulkerson algorithm.
Constraints:
2 ≤ N ≤ 50
Directed graph with capacities
Input Format:
First line → Two integers N E
Next E lines → Three integers U V C (directed edge from U to V with capacity C)
Problem Statement: A university anti-plagiarism system detects if any substring of document A of length L exactly matches any substring of document B of length L. Use Rabin-Karp rolling hash for efficiency. Print the starting indices (0-based) in both documents where the first match is found, or "No Match".
First line → String A
Second line → String B
Third line → Integer L
Output Format:
"Match at A[i] and B[j]" or "No Match"
Sample Input 1:
abcxyz
xyzabc
3
Sample Output 1:
Match at A[0] and B[3]
❓ Problem 76 — The Minimum Cost to Hire Workers
🏷️ Prime | Greedy/Heap | Hard
Problem Statement: A company wants to hire exactly K workers from a pool of N workers. Each worker has a quality and a wage expectation. The company must pay each worker at least their expected wage AND proportional to quality (all workers in the group are paid at the same wage-to-quality ratio). Find the minimum cost to hire exactly K workers (output as a float rounded to 5 decimal places).
Constraints:
1 ≤ K ≤ N ≤ 10^4
1 ≤ quality[i] ≤ 10^4
1 ≤ wage[i] ≤ 10^4
Input Format:
First line → Two integers N K
Next N lines → Two integers quality wage
Output Format:
Minimum cost rounded to 5 decimal places
Sample Input 1:
3 2
10 70
20 50
5 30
Sample Output 1:
105.00000
❓ Problem 77 — The Burrows-Wheeler String Transform
🏷️ Prime | String/Cyclic Rotation | Very Hard
Problem Statement: The Burrows-Wheeler Transform (BWT) is used in data compression. Given a string S, generate all rotations, sort them lexicographically, and output the last column of the sorted rotation matrix. Also output the row index where the original string appears in the sorted order (0-indexed).
Constraints:
1 ≤ len(S) ≤ 1000
String contains lowercase letters only
Input Format:
Single line → String S
Output Format:
First line → BWT string (last column)
Second line → Index of original string
Sample Input 1:
banana
Sample Output 1:
annb$aa
(Standard BWT appends $ to mark end — candidates follow convention)
❓ Problem 78 — The Minimum Edit Distance Engine
🏷️ Prime | DP | Hard
Problem Statement: A spell-checker computes how many minimum operations (insert, delete, or replace one character) are needed to transform word A into word B. This is the Edit Distance (Levenshtein Distance). Given two words, compute it.
Constraints:
0 ≤ len(A), len(B) ≤ 1000
Input Format:
First line → String A
Second line → String B
Output Format:
Single integer → Minimum edit distance
Sample Input 1:
horse
ros
Sample Output 1:
3
Sample Input 2:
intention
execution
Sample Output 2:
5
❓ Problem 79 — The Tarjan’s SCC Finder
🏷️ Prime | Graph/DFS/SCC | Very Hard
Problem Statement: A telecommunications company has N servers connected by directed links. They want to identify Strongly Connected Components (SCCs) — groups of servers where every server can reach every other server in the group. Use Tarjan’s Algorithm and print each SCC.
Constraints:
1 ≤ N ≤ 1000
Directed graph
Input Format:
First line → Two integers N E
Next E lines → Two integers U V (directed edge)
Output Format:
Print each SCC on a separate line (nodes space-separated, in any order)
Sample Input 1:
5 5
1 2
2 3
3 1
3 4
4 5
Sample Output 1:
1 2 3
4
5
❓ Problem 80 — The Convex Hull Security Perimeter
🏷️ Prime | Geometry/Convex Hull | Very Hard
Problem Statement: A military base needs to erect a fence around all its watchtowers. Given N watchtower coordinates, find the minimum perimeter fence that encloses all towers — i.e., the Convex Hull of the points. Use Graham Scan or Jarvis March. Print the vertices of the convex hull in counter-clockwise order starting from the bottom-most point, and the perimeter length rounded to 2 decimal places.
Constraints:
3 ≤ N ≤ 10^4
0 ≤ x, y ≤ 10^4
Input Format:
First line → Integer N
Next N lines → Two integers x y (coordinates)
Output Format:
First line → Convex hull vertices (x,y pairs) in CCW order
Second line → "Perimeter: X.XX"
Sample Input 1:
5
0 0
1 1
2 2
0 2
2 0
Sample Output 1:
(0,0) (2,0) (2,2) (0,2)
Perimeter: 8.00
❓ Problem 81 — The Alien Number Theory (Big Modular Exponentiation)
🏷️ Prime | Math/Number Theory | Hard
Problem Statement: A cryptography algorithm requires computing (A^B) mod M where A and B can be extremely large. Brute force is too slow — use fast modular exponentiation (binary exponentiation) to compute it efficiently in O(log B) time.
Constraints:
1 ≤ A ≤ 10^18
1 ≤ B ≤ 10^18
1 ≤ M ≤ 10^9
Input Format:
Three integers on separate lines: A, B, M
Output Format:
Single integer → (A^B) mod M
Sample Input 1:
2
10
1000
Sample Output 1:
24
Sample Input 2:
3
200
1000000007
Sample Output 2:
884337246
❓ Problem 82 — The Longest Increasing Subsequence with Count
🏷️ Prime | DP | Hard
Problem Statement: A stock analyst is analyzing stock prices over N days. She wants to find both the length of the Longest Increasing Subsequence (LIS) and the number of such subsequences of that length. Print both values. Count modulo 10^9+7.
Constraints:
1 ≤ N ≤ 2000
1 ≤ price[i] ≤ 10^9
Input Format:
First line → Integer N
Second line → N space-separated integers
Output Format:
First line → "LIS Length: X"
Second line → "Count: Y"
Sample Input 1:
6
1 3 5 4 7 8
Sample Output 1:
LIS Length: 5
Count: 2
❓ Problem 83 — The Painter’s Partition Problem
🏷️ Prime | Binary Search + Greedy | Hard
Problem Statement: N boards need to be painted. There are K painters. Each painter can paint contiguous boards only. The time taken to paint a board = board length. All painters work simultaneously. Minimize the time taken by the slowest painter (i.e., minimize the maximum sum of any contiguous partition of N boards into K groups).
Constraints:
1 ≤ K ≤ N ≤ 10^4
1 ≤ board[i] ≤ 10^6
Input Format:
First line → Two integers N K
Second line → N space-separated integers (board lengths)
Output Format:
Single integer → Minimum time (maximum partition sum minimized)
❓ Problem 84 — The Interval Scheduling Meeting Rooms
🏷️ Prime | Greedy/Sorting | Hard
Problem Statement: A conference centre manager receives N meeting requests. Each meeting has a start and end time. She wants to find the minimum number of meeting rooms required to accommodate all meetings (no two meetings in the same room can overlap).
Constraints:
1 ≤ N ≤ 10^5
0 ≤ start[i] < end[i] ≤ 10^9
Input Format:
First line → Integer N
Next N lines → Two integers start end
Output Format:
Single integer → Minimum rooms required
Sample Input 1:
4
0 30
5 10
15 20
5 25
Sample Output 1:
3
❓ Problem 85 — The Regular Expression Matcher
🏷️ Prime | DP/String | Very Hard
Problem Statement: Implement a regular expression matcher supporting:
. → Matches any single character
* → Matches zero or more of the preceding element
The match must cover the entire input string (not partial). Print "Match" or "No Match".
Constraints:
0 ≤ len(s), len(p) ≤ 1000
s contains lowercase letters
p contains lowercase letters, '.', '*'
Input Format:
First line → String s (text)
Second line → String p (pattern)
Output Format:
"Match" or "No Match"
Sample Input 1:
aa
a*
Sample Output 1:
Match
Sample Input 2:
ab
.*
Sample Output 2:
Match
Sample Input 3:
aab
c*a*b
Sample Output 3:
Match
❓ Problem 86 — The Minimum Window Substring
🏷️ Prime | Sliding Window | Hard
Problem Statement: A search engine’s highlight feature needs to find the minimum window substring of string S that contains all characters of string T (including duplicates). If no valid window exists, print "".
Constraints:
1 ≤ len(S) ≤ 10^5
1 ≤ len(T) ≤ 10^4
Input Format:
First line → String S
Second line → String T
Output Format:
Minimum window substring, or "" if not possible
Sample Input 1:
ADOBECODEBANC
ABC
Sample Output 1:
BANC
Sample Input 2:
a
aa
Sample Output 2:
❓ Problem 87 — The Number of Islands (Union-Find)
🏷️ Prime | Union-Find/DFS | Hard
Problem Statement: A geographer is analysing satellite images. A 2D grid contains 1 (land) and 0 (water). An island is a group of 1s connected horizontally or vertically. Count the total number of distinct islands. Use Union-Find (Disjoint Set Union) for maximum efficiency.
Constraints:
1 ≤ N, M ≤ 300
grid[i][j] ∈ {0, 1}
Input Format:
First line → Two integers N M
Next N lines → M space-separated integers (0 or 1)
Output Format:
Single integer → Number of islands
Sample Input 1:
4 5
1 1 1 1 0
1 1 0 1 0
1 1 0 0 0
0 0 0 0 0
Sample Output 1:
1
Sample Input 2:
4 5
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
Sample Output 2:
3
❓ Problem 88 — The Traveling Salesman Problem (Small N)
🏷️ Prime | DP/Bitmask | Very Hard
Problem Statement: A delivery agent starts from city 0 and must visit all N cities exactly once, then return to city 0. Given the distance matrix, find the minimum total travel distance (TSP using Bitmask DP for N ≤ 20).
First line → Integer N
Next N lines → N space-separated integers (distance matrix row i)
Output Format:
Single integer → Minimum tour distance
Sample Input 1:
4
0 10 15 20
10 0 35 25
15 35 0 30
20 25 30 0
Sample Output 1:
80
❓ Problem 89 — The Suffix Array Construction
🏷️ Prime | String/Suffix Array | Very Hard
Problem Statement: A bioinformatics tool indexes DNA sequences using a Suffix Array — an array of the starting indices of all suffixes of a string, sorted in lexicographic order. Given a DNA string S, construct and output its suffix array.
Constraints:
1 ≤ len(S) ≤ 10^5
String contains only A, C, G, T
Input Format:
Single line → DNA string S
Output Format:
Space-separated integers → Suffix array (starting indices 0-indexed)
Sample Input 1:
ACGT
Sample Output 1:
0 1 2 3
Sample Input 2:
banana
Sample Output 2:
5 3 1 0 4 2
❓ Problem 90 — The Count of Inversions (Merge Sort)
🏷️ Prime | Divide & Conquer | Hard
Problem Statement: A stock market analyst counts inversions in a price array — a pair (i, j) where i < j but arr[i] > arr[j] represents a bad trend. Count the total number of inversions using modified Merge Sort in O(n log n).
Constraints:
1 ≤ N ≤ 10^5
1 ≤ arr[i] ≤ 10^9
Input Format:
First line → Integer N
Second line → N space-separated integers
Problem Statement: Two players play Nim: there are N piles of stones. Players take turns. On each turn a player removes any positive number of stones from exactly one pile. The player who takes the last stone wins. Both players play optimally.
Given the pile sizes, determine who wins: “First Player Wins” or “Second Player Wins”.
The optimal strategy uses XOR: if XOR of all pile sizes ≠ 0, first player wins.
Constraints:
1 ≤ N ≤ 100
0 ≤ pile[i] ≤ 10^9
Input Format:
First line → Integer N
Second line → N space-separated pile sizes
Output Format:
"First Player Wins" or "Second Player Wins"
Sample Input 1:
3
3 4 5
Sample Output 1:
First Player Wins
Sample Input 2:
3
1 2 3
Sample Output 2:
Second Player Wins
Explanation: XOR(3,4,5) = 2 ≠ 0 → First wins. XOR(1,2,3) = 0 → Second wins.
❓ Problem 93 — The Shortest Superstring
🏷️ Prime | DP/Greedy | Very Hard
Problem Statement: A DNA sequencing lab receives N DNA fragments. They want to reconstruct the shortest possible DNA strand that contains all fragments as substrings. This is the Shortest Superstring Problem. For small N (≤ 12), use Bitmask DP. Return the minimum length of such a superstring.
Constraints:
1 ≤ N ≤ 12
1 ≤ len(each fragment) ≤ 50
Input Format:
First line → Integer N
Next N lines → DNA fragments
Output Format:
Single integer → Minimum superstring length
Sample Input 1:
3
abcd
cdef
efgh
Sample Output 1:
8
Explanation: Superstring: abcdefgh length 8 (cd overlaps, ef overlaps) ✅
❓ Problem 94 — The Segment Overlap Merge
🏷️ Prime | Sorting/Intervals | Hard
Problem Statement: A video editing software has N timeline clips, each represented as an interval [start, end]. The software needs to merge all overlapping clips into the minimum number of non-overlapping intervals. Two intervals overlap if one starts before the other ends (or they touch at a boundary).
Constraints:
1 ≤ N ≤ 10^4
0 ≤ start ≤ end ≤ 10^4
Input Format:
First line → Integer N
Next N lines → Two integers start end
Output Format:
Merged intervals, one per line: "start end"
Sample Input 1:
5
1 3
2 6
8 10
15 18
9 12
Sample Output 1:
1 6
8 12
15 18
❓ Problem 95 — The K-th Smallest in Matrix
🏷️ Prime | Binary Search/Heap | Hard
Problem Statement: A satellite imaging system stores data in an N×N matrix where each row and column is sorted in ascending order. Given K, find the K-th smallest element in the matrix.
Constraints:
1 ≤ N ≤ 300
1 ≤ K ≤ N²
-10^9 ≤ matrix[i][j] ≤ 10^9
Input Format:
First line → Two integers N K
Next N lines → N space-separated integers per row
Output Format:
Single integer → K-th smallest element
Sample Input 1:
3 8
1 5 9
10 11 13
12 13 15
Sample Output 1:
13
❓ Problem 96 — The 2-SAT Boolean Satisfiability
🏷️ Prime | Graph/SCC | Very Hard
Problem Statement: A circuit designer has N boolean variables and M clauses, each of the form (xi OR xj) or (xi OR ¬xj) or (¬xi OR ¬xj). This is the 2-SAT Problem. Determine if there exists a valid assignment of True/False to all variables that satisfies all clauses. If yes, print "Satisfiable" and a valid assignment; else "Unsatisfiable". Solve using SCC + Topological Sort.
Constraints:
1 ≤ N ≤ 10^4
1 ≤ M ≤ 10^5
Input Format:
First line → Two integers N M
Next M lines → Two integers i j
(positive = xi, negative = ¬xi)
Output Format:
"Satisfiable" + assignment on next line, or "Unsatisfiable"
Sample Input 1:
2 3
1 2
-1 2
1 -2
Sample Output 1:
Satisfiable
x1=True x2=True
❓ Problem 97 — The Heavy-Light Decomposition
🏷️ Prime | Tree/HLD | Very Hard
Problem Statement: A power grid is modelled as a tree of N nodes (power stations). Maintenance engineers make two types of queries repeatedly:
UPDATE u v x → Add x to all nodes on the path from u to v
QUERY u v → Find the maximum node value on the path from u to v
Use Heavy-Light Decomposition + Segment Tree for O(log² n) per query.
❓ Problem 99 — The Polynomial Multiplication via FFT
🏷️ Prime | FFT/Math | Very Hard
Problem Statement: A signal processing system needs to multiply two large polynomials. Given polynomial A of degree N and polynomial B of degree M (both given as coefficient arrays), compute A × B using the Fast Fourier Transform (FFT) in O((N+M) log(N+M)). Print the coefficients of the resulting polynomial from degree 0 to degree N+M.
Constraints:
1 ≤ N, M ≤ 10^5
0 ≤ coefficient ≤ 100
Input Format:
First line → Integer N (degree of A)
Second line → (N+1) space-separated integers (coefficients of A, from degree 0)
Third line → Integer M (degree of B)
Fourth line → (M+1) space-separated integers (coefficients of B)
Output Format:
(N+M+1) space-separated integers → Coefficients of A×B
❓ Problem 100 — The Final Boss: Offline LCA + Difference Array on Tree
🏷️ Prime | Tree/LCA/Euler Tour | Very Hard
Problem Statement: A research institute models dependency relationships as a rooted tree (root = node 1) with N nodes. A professor issues Q queries, each of the form (u, v, x): add x to every node on the path from u to v. After all updates, print the final value of each node.
Use:
Binary Lifting for O(log n) LCA
Euler Tour + Difference Array on Tree for path updates in O(N + Q log N)
Constraints:
1 ≤ N ≤ 10^5
1 ≤ Q ≤ 10^5
1 ≤ x ≤ 10^4
Input Format:
First line → Two integers N Q
Next (N-1) lines → Edges of the tree (undirected)
Next Q lines → Three integers u v x
Output Format:
N space-separated integers → Final value of each node (1 to N)