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.
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
- Advanced Section: 1 coding question, higher difficulty, 45–60 minutes
- Languages allowed: Python, Java, C, C++
- TITA questions: Type In The Answer — no options, must match exactly
- Pattern: Story wraps the algorithm. Decode the story first.
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.
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.
Two-pointer: maintain a write pointer for non-zero values. Place each non-zero at the pointer, then backfill remaining positions with zeros.
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)
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.
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.
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)
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.
Track the minimum price seen so far. At each price compute profit = price - min_so_far. Update the maximum profit. Single pass.
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)
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.
Each handshake involves 2 unique people. Formula: N*(N-1)//2. Pure math — no loops needed.
t = int(input())
for _ in range(t):
n = int(input())
print(n * (n - 1) // 2)
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.
Slice the string into chunks of size L. Count 'a' in each chunk and track the maximum.
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)
An intelligence agency assigns codes by repeatedly summing digits of N for R times. Return the final result. If R=0, return 0.
Iteratively compute digit sum R times. Optimisation: if n < 10 at any point, break early — single digit wont change.
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)
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.
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.
n = int(input())
arr = [int(input()) for _ in range(n)]
result = 0
for x in arr:
result ^= x
print(result)
At airport security, items are tagged: 0=safe, 1=neutral, 2=dangerous. Sort all items in a single pass without extra array.
Dutch National Flag: three pointers low, mid, high. If arr[mid]==0 swap with low; if ==2 swap with high; else advance mid.
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)
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.
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)!
import math n = int(input()) print(2 * math.factorial(n - 2))
Given a positive integer N, convert it to binary, toggle all bits, and return the decimal value.
Create a mask of all 1s with the same bit length as N: mask = (1 << n.bit_length()) - 1. XOR N with mask.
n = int(input()) mask = (1 << n.bit_length()) - 1 print(n ^ 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.
For each formation take the set of unique characters. Intersect all sets. Count elements in the final intersection.
n = int(input())
sets = [set(input().strip()) for _ in range(n)]
common = sets[0]
for s in sets[1:]:
common &= s
print(len(common))
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.
Scan left to right tracking the running maximum. If current element > running max, it's a new leader.
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)
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.
Split by dot. Check: starts alphanumeric, no spaces, exactly one dot, valid extension.
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")
A college has N subjects to schedule per day. Each subject must appear exactly once. How many different daily timetables (arrangements) are possible?
This is simply N! (N factorial). Each arrangement is a permutation of N subjects.
import math n = int(input()) print(math.factorial(n))
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.
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).
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)
Array Manipulation
Arrays are the most tested data structure in TCS NQT. Know these 10 patterns cold.
Given an array of integers, find the second largest unique element. If no second largest exists, print -1.
Convert to set, sort descending. Second element is the answer if it exists.
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)
Given an array of N integers, reverse the array in-place and print the result.
Use Python's slice notation arr[::-1] for a clean one-liner reversal.
n = int(input()) arr = [int(input()) for _ in range(n)] print(*arr[::-1])
Given an array of integers, remove all duplicate elements and print unique elements in their original order of first occurrence.
Track seen elements with a set while preserving insertion order.
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)
Given an array of integers and target sum K, find and print all unique pairs (a,b) where a+b==K and a<=b.
Use a hash set. For each element, check if K-element exists in seen set. Print unique pairs only.
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)
Given an array of N integers, print the frequency of each unique element in the order they first appear.
Use an OrderedDict to count while preserving first-appearance order.
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}")
Given an array of integers (may contain negatives), find the maximum sum of any contiguous subarray.
Kadane's: track current_sum and max_sum. At each element: current_sum = max(element, current_sum + element).
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)
Given an array and integer K, rotate the array to the right by K positions.
Normalise K = K%n. Rotated = arr[-K:] + arr[:-K].
n = int(input())
arr = [int(input()) for _ in range(n)]
k = int(input()) % n
if k:
arr = arr[-k:] + arr[:-k]
print(*arr)
Given an array containing N-1 distinct integers in range 1 to N, find the missing number.
Expected sum = N*(N+1)//2. Missing = expected - actual sum.
n = int(input()) arr = [int(input()) for _ in range(n-1)] print(n*(n+1)//2 - sum(arr))
Array of n+1 integers with values in [1,n]. Exactly one number repeats. Find it without modifying the array and using O(1) space.
Treat array as linked list. Use Floyd's cycle detection. Phase 1: find meeting point. Phase 2: find cycle entry.
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)
Given an unsorted array, find the length of the longest sequence of consecutive integers.
Convert to set. For each element that is a sequence start (element-1 not in set), count consecutive elements.
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)
String Operations
String problems appear in the Foundation section. Python string methods make most of these elegant one-liners.
Given a string, check if it reads the same forwards and backwards (case-insensitive). Print 'Yes' or 'No'.
Convert to lowercase. Compare string with its reverse using slicing.
s = input().strip().lower()
print("Yes" if s == s[::-1] else "No")
Given two strings, check if they are anagrams (same characters with same frequencies, case-insensitive).
Use Counter from collections to compare character frequencies.
from collections import Counter
s1 = input().strip().lower()
s2 = input().strip().lower()
print("Yes" if Counter(s1) == Counter(s2) else "No")
Given a string, count the number of vowels and consonants (ignore spaces and special characters).
Iterate characters. Count alphabetic ones in vowel set vs not.
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}")
Given a string, find and print the first character that does not repeat. If all characters repeat, print -1.
Count frequencies using Counter. Scan original string for first character with frequency 1.
from collections import Counter
s = input().strip()
freq = Counter(s)
for c in s:
if freq[c] == 1:
print(c)
break
else:
print(-1)
Given a sentence, reverse the order of words (not individual characters). Extra spaces should be removed.
Split the string by whitespace (handles multiple spaces), reverse the list, join.
s = input()
print(' '.join(s.split()[::-1]))
Given a string, find the length of the longest substring containing no repeating characters.
Sliding window with a set: expand right, shrink from left when a duplicate is found.
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)
Given a text string and a pattern, count the number of times the pattern appears (overlapping matches counted).
Loop from 0 to len(text)-len(pat)+1 and check each window.
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)
Compress a string using run-length encoding: replace consecutive repeating characters with character + count. If compressed >= original length, return original.
Iterate tracking current character and count. Build compressed string. Return shorter of the two.
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)
Given two strings S1 and S2 of the same length, check if S2 is a rotation of S1.
S2 is a rotation of S1 if and only if S2 is a substring of S1+S1.
s1 = input().strip()
s2 = input().strip()
print("Yes" if len(s1)==len(s2) and s2 in s1+s1 else "No")
Given N strings, find their longest common prefix. If there is no common prefix, print an empty string.
Sort the strings lexicographically. Compare only the first and last string character by character.
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 "")
Number Theory & Mathematics
Prime checks, factorials, Fibonacci, GCD/LCM appear in both Foundation and Advanced sections.
Given a positive integer N, determine if it is prime. Print 'Prime' or 'Not Prime'.
Check divisibility from 2 to sqrt(N). Any divisor found means not prime.
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")
Given two integers A and B, print their GCD (Greatest Common Divisor) and LCM (Least Common Multiple).
Use Euclidean algorithm for GCD. LCM = (a * b) // GCD.
from math import gcd
a, b = int(input()), int(input())
g = gcd(a, b)
print(f"GCD:{g} LCM:{(a*b)//g}")
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.
Count digits k. Compute sum of digit^k. Compare with original number.
n = int(input())
digits = str(n)
k = len(digits)
print("Yes" if n == sum(int(d)**k for d in digits) else "No")
Print the first N terms of the Fibonacci series (starting from 0).
Iteratively compute: a, b = 0, 1 then repeatedly a, b = b, a+b.
n = int(input())
a, b = 0, 1
fib = []
for _ in range(n):
fib.append(a)
a, b = b, a + b
print(*fib)
Given a non-negative integer N, compute N! using a loop (not the math.factorial built-in).
Iteratively multiply from 1 to N. Base case: 0! = 1.
n = int(input())
result = 1
for i in range(2, n+1):
result *= i
print(result)
A perfect number equals the sum of its proper divisors (all divisors excluding itself). Check if N is perfect.
Sum all divisors from 1 to n-1. Compare with n.
n = int(input())
total = sum(i for i in range(1, n) if n % i == 0)
print("Yes" if total == n else "No")
Given a decimal integer N, print its binary, octal, and hexadecimal representations (without prefixes).
Use Python built-ins: bin(), oct(), hex() and strip the prefix (0b, 0o, 0x).
n = int(input()) print(bin(n)[2:], oct(n)[2:], hex(n)[2:])
Given a positive integer N, find and print all its prime factors (with repetition).
Divide N by 2 while divisible, then check odd divisors from 3 to sqrt(N).
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)
Given base B and exponent E (both non-negative integers), compute B^E without using ** or pow(). Handle E=0 as 1.
Exponentiation by squaring: halve E each step. If E is odd, multiply result by base.
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)
Given a non-negative integer N, repeatedly sum its digits until the result is a single digit. Print the digital root.
Digital root formula: if n==0 return 0, else return 1 + (n-1) % 9. This is O(1).
n = int(input()) print(0 if n == 0 else 1 + (n - 1) % 9)
Sorting & Searching
Sorting problems test algorithmic thinking. TCS sometimes asks you to implement a specific sort from scratch.
Implement bubble sort to sort an array of N integers in ascending order without using Python's built-in sort.
Repeatedly step through the list comparing adjacent elements and swapping if out of order. Repeat N times.
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)
Given a sorted array of N integers and a target T, perform binary search. Print the 0-based index if found, else -1.
Standard binary search: low, high pointers. Mid = (low+high)//2. Adjust based on comparison.
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)
Given an array of N integers and integer K, find the Kth largest element.
Sort in descending order and return element at index K-1. Or use min-heap of size K for O(n log k).
n = int(input()) arr = [int(input()) for _ in range(n)] k = int(input()) arr.sort(reverse=True) print(arr[k-1])
Given two sorted arrays of sizes M and N, merge them into a single sorted array.
Two-pointer merge: compare front elements of both arrays, pick the smaller one.
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)
Given an array, determine the minimum number of bubble sort passes needed to fully sort it. Print the count.
Simulate bubble sort counting passes. A pass that makes no swaps is the first unnecessary pass.
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)
Pattern Printing
Pattern questions test nested loop understanding and appear occasionally in TCS Foundation section.
Print a right-angled triangle pattern of stars with N rows. Row i has i stars.
For each row i from 1 to N, print i stars.
n = int(input())
for i in range(1, n+1):
print("*" * i)
Print a number pyramid with N rows. Row i contains numbers 1 to i separated by spaces.
For each row i, print numbers 1 to i.
n = int(input())
for i in range(1, n+1):
print(*range(1, i+1))
Print an inverted right-angled triangle of stars with N rows starting from N stars down to 1.
Loop from N down to 1 printing that many stars per row.
n = int(input())
for i in range(n, 0, -1):
print("*" * i)
Print a diamond pattern of stars with N rows (N must be odd). The widest row (middle) has N stars.
Print upper half: rows with 1,3,...,N stars with padding. Then lower half: N-2,...,1 stars.
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)
Recursion & Dynamic Programming
These appear in the Advanced coding section. Practise these if you are targeting TCS Digital or higher packages.
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.
Recursive: move N-1 disks to auxiliary, move Nth disk to destination, move N-1 from auxiliary to destination.
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")
Given two strings S1 and S2, find the length of their Longest Common Subsequence.
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.
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])
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.
Classic 0/1 knapsack DP. dp[i][w] = max value using first i items with capacity w. Include or exclude each item.
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])
Given an array of N non-negative integers and a target sum S, count the number of subsets that sum exactly to S.
Recursive solution: at each element, either include it (subtract from S) or exclude it. Base cases: S==0 → 1 way, no elements → 0 ways.
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))
Miscellaneous & Logic
These don't fit a neat category but have appeared in real TCS NQT exam slots.
Given a plaintext string and shift K, encrypt using Caesar cipher (shift each letter by K, wrap around). Preserve case and non-alphabetic characters.
For each character: compute position, apply shift mod 26, convert back. Non-alpha characters stay unchanged.
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))
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.
Rule: (divisible by 4 AND not divisible by 100) OR divisible by 400.
y = int(input())
if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0):
print("Leap Year")
else:
print("Not Leap Year")
Frequently Asked Questions
Want Complete TCS NQT Preparation?
Explore all CampusMonk courses — mock tests, recorded programs, and full placement packs.
📚 Browse All Courses →