🔥 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.

CampusMonk 60 Verified Questions Python Solutions Updated 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
  • 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.
⚡ 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
Easy Arrays / 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
Easy Date 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
Easy Greedy
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
Easy Combinatorics
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
Easy Strings
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
Medium Math
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
Easy XOR
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
Medium Arrays
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
Medium Math
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
Easy Bit 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.
Python Solution ✔ Verified
n = int(input())
mask = (1 << n.bit_length()) - 1
print(n ^ mask)
Time: O(1) Space: O(1)
11
Easy Sets
Radiant Gemstones

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
Easy Arrays
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
Easy Strings
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
Easy Combinatorics
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
Medium Arrays
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
Easy Arrays
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
Easy Arrays
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
Easy Arrays
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
Medium Arrays
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
Easy Arrays
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
Medium Arrays
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
Easy Arrays
Rotate Array by K Positions (Right Rotation)

Given an array and integer K, rotate the array to the right by K positions.

Input 1
[1,2,3,4,5], K=2
Output 1
4 5 1 2 3
Input 2
[1,2,3], K=4
Output 2
3 1 2
⚙ Approach
Normalise K = K%n. Rotated = arr[-K:] + arr[:-K].
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n)]
k = int(input()) % n
if k:
    arr = arr[-k:] + arr[:-k]
print(*arr)
Time: O(n) Space: O(n)
23
Easy Arrays
Find the Missing Number in 1 to N

Given an array containing N-1 distinct integers in range 1 to N, find the missing number.

Input 1
[1,2,4,5], N=5
Output 1
3
Input 2
[2,3,4,5], N=5
Output 2
1
⚙ Approach
Expected sum = N*(N+1)//2. Missing = expected - actual sum.
Python Solution ✔ Verified
n = int(input())
arr = [int(input()) for _ in range(n-1)]
print(n*(n+1)//2 - sum(arr))
Time: O(n) Space: O(1)
24
Medium Arrays
Find the Duplicate Number (Floyd's Cycle)

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.

Input 1
[1,3,4,2,2]
Output 1
2
Input 2
[3,1,3,4,2]
Output 2
3
⚙ Approach
Treat array as linked list. Use Floyd's cycle detection. Phase 1: find meeting point. Phase 2: find cycle entry.
Python Solution ✔ Verified
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
Medium Arrays
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
Easy Strings
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
Easy Strings
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
Easy Strings
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
Easy Strings
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
Easy Strings
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
Medium Strings
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
Easy Strings
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
Easy Strings
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
Medium Strings
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
Medium Strings
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
Easy Number 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
Easy Number 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
Easy Number 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
Easy Math
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
Easy Math
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
Easy Number 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
Easy Number 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
Medium Number 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
Easy Math
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
Easy Math
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
Easy Sorting
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
Easy Searching
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
Medium Sorting
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
Medium Sorting
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
Medium Sorting
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
Easy Patterns
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
Easy Patterns
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
Easy Patterns
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
Medium Patterns
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
Medium Recursion
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
Medium Dynamic 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
Medium Dynamic 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
Medium Recursion
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
Easy Miscellaneous
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
Easy Miscellaneous
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.
What type of coding questions does TCS NQT ask?
TCS NQT asks story-based problems (chocolate factory, Sunday count, stock profit), array manipulation, string operations, number theory, sorting, and combinatorics problems.
Is TCS NQT coding round difficult?
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.

📚 Browse All Courses →