TCS NQT and Infosys Coding Questions: Practice in Python
Campus and off-campus coding rounds for service-company hiring, such as TCS NQT and Infosys assessments, are not like a product-company interview. There is no interviewer to talk to, no partial credit for a good idea, and the judge is an autograder that runs your code on hidden inputs. The problems are usually easier than LeetCode mediums. What eliminates people is everything around the algorithm: reading input the way the judge expects, missing an edge case, and spending forty minutes on the first question.
This guide is built around that reality. It covers the input handling that fails silently, a time plan, and seven representative problems with Python solutions whose outputs were actually run. One honest caveat first: these are practice problems in the style of such tests, not questions copied from any exam paper, and no one outside the exam publishes the real ones.
Check the current format yourself
Exam patterns change between hiring cycles, and third-party sites often disagree. Recent write-ups of the TCS NQT 2026 pattern describe a coding block of two questions with C, C++, Java and Python allowed, but they quote the allotted time differently, from a short 30-minute block to a 90-minute Advanced Coding section. Infosys tests also vary by role. Treat any number you read on a blog, including here, as a hint, and confirm the section timing, language list and marking rules on the official TCS iON NQT page or in your Infosys invitation before you plan your day.
Rule one: read input the way a judge feeds it
Autograders pipe a text file into your program. If your parsing assumes tidy lines, a stray blank line or trailing space ends in a runtime error, and the judge reports it as a failed test, not a typo. Reading everything at once and splitting on whitespace ignores all of that.
import sys
def main():
data = sys.stdin.read().split()
n = int(data[0])
nums = list(map(int, data[1:1 + n]))
k = int(data[1 + n])
k %= n
print(*(nums[-k:] + nums[:-k] if k else nums))
main()
Fed the clean input 7 / 1 2 3 4 5 6 7 / 3, it printed 5 6 7 1 2 3 4. Fed a messy version with trailing spaces and an extra blank line, it printed the same thing. The line-by-line version using int(input()) and input().split() crashed on that messy input with ValueError: invalid literal for int() with base 10: ''.
Two more habits from the same test run. First, print(*list) prints space-separated values with no brackets or commas, which is what most judges expect. Second, speed: reading 200,000 lines with input() took 0.146 s against 0.040 s for sys.stdin.readline. That is irrelevant for ten numbers and decisive for large tests.
When the first line is the number of test cases, keep a position pointer into the token list:
def main():
data = sys.stdin.read().split()
t = int(data[0]); pos = 1
out = []
for _ in range(t):
n = int(data[pos]); pos += 1
arr = list(map(int, data[pos:pos + n])); pos += n
out.append(str(sum(arr)))
print('\n'.join(out))
# input '2 / 3 / 1 2 3 / 2 / 10 20' -> prints 6 and 30 on separate lines
Rule two: know the Python traps that change answers
7 / 2 # -> 3.5 true division always returns a float
7 // 2 # -> 3 floor division
-7 // 2 # -> -4 floors toward negative infinity
int(-7/2) # -> -3 truncates toward zero, a different answer
round(2.5), round(3.5) # -> 2, 4 banker’s rounding, not 2.5 → 3
A C or Java programmer expects -7 / 2 to be −3, so a direct port to Python quietly returns −4. Use int(a / b) only when the problem truly wants truncation, and avoid round when the statement says “round half up”.
Seven practice problems
1. Second largest distinct element
Return the second largest distinct value, or None if there is none. One pass, no sorting. The duplicate check is what breaks most first attempts.
def second_largest(a):
first = second = None
for x in a:
if first is None or x > first:
first, second = x, first
elif x != first and (second is None or x > second):
second = x
return second
second_largest([12, 35, 1, 10, 34, 1]) # -> 34
second_largest([5, 5, 5]) # -> None
second_largest([-3, -1, -2]) # -> -2
second_largest([]) # -> None
On 5,000 random lists it matched sorted(set(a))[-2] every time.
2. Rotate an array right by k
The edge cases are the whole problem: k larger than the length, an empty list, k that is a multiple of the length.
def rotate(a, k):
if not a:
return a
k %= len(a)
return a[-k:] + a[:-k] if k else a[:]
rotate([1, 2, 3, 4, 5, 6, 7], 3) # -> [5, 6, 7, 1, 2, 3, 4]
rotate([1, 2, 3], 5) # -> [2, 3, 1]
rotate([], 3) # -> []
rotate([9], 100) # -> [9]
3. Prime check and primes up to N
Test divisors only up to the square root, skipping even numbers. For “list every prime up to N”, a sieve is faster by a wide margin.
def is_prime(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
def sieve(n):
if n < 2:
return []
s = bytearray([1]) * (n + 1)
s[0] = s[1] = 0
for i in range(2, int(n ** 0.5) + 1):
if s[i]:
s[i * i::i] = bytearray(len(s[i * i::i]))
return [i for i in range(n + 1) if s[i]]
[n for n in range(1, 31) if is_prime(n)] # -> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
len(sieve(1_000_000)) # -> 78498
The sieve and the trial-division check agree up to 30, and 78,498 is the known count of primes below one million.
4. Pyramid pattern
Pattern printing is a staple. Derive the spaces and stars per row instead of memorising shapes: row i of n has n - i spaces and 2*i - 1 stars.
def pyramid(n):
return '\n'.join(' ' * (n - i) + '*' * (2 * i - 1) for i in range(1, n + 1))
print(pyramid(4))
# *
# ***
# *****
# *******
Judges compare output character by character, so trailing spaces and a missing final newline can matter. Generate exactly what the statement shows.
5. Armstrong numbers
A number is an Armstrong number if the sum of its digits, each raised to the number of digits, equals the number itself.
def is_armstrong(n):
d = str(n)
p = len(d)
return sum(int(c) ** p for c in d) == n
[n for n in range(1, 1000) if is_armstrong(n)]
# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]
6. Run-length compression
def compress(s):
if not s:
return ''
out, cnt = [], 1
for i in range(1, len(s) + 1):
if i < len(s) and s[i] == s[i - 1]:
cnt += 1
else:
out.append(s[i - 1] + (str(cnt) if cnt > 1 else ''))
cnt = 1
return ''.join(out)
compress('aaabbc') # -> 'a3b2c'
compress('abc') # -> 'abc'
compress('') # -> ''
compress('zzzzzzzzzzzz') # -> 'z12'
The loop runs to len(s) + 1 so the last group is flushed inside the loop, which avoids a repeated block after it. The last test shows a count above nine is written as two digits.
7. Count pairs with a given sum
The brute force checks every pair in O(n²) and will time out on large tests. Count as you go with a frequency map instead. This is the idea from the Two Sum walkthrough, extended to count duplicates.
from collections import Counter
def count_pairs(a, k):
seen = Counter()
c = 0
for x in a:
c += seen[k - x]
seen[x] += 1
return c
count_pairs([1, 5, 7, -1, 5], 6) # -> 3
count_pairs([1, 1, 1, 1], 2) # -> 6
In the second call, four equal values give C(4, 2) = 6 pairs, which is exactly why the counter must count duplicates. A 3,000-case random test against the O(n²) version matched every time.
A time plan that survives a bad first question
- Read both questions first, two minutes in total, and start with the one you can solve fastest.
- Write the brute force in your head and estimate whether the input size allows it. Constraints like n up to 105 rule out O(n²).
- Run the sample, then your own edge cases: empty input, a single element, all equal values, negatives, the largest allowed size.
- Cap each question. If one is stuck after about half of your time, submit a partial solution that passes some tests and move on, because partial test credit often counts.
What to practise, and in what order
Arrays, strings and number problems cover most of this style. Start with the patterns in two pointers and the sliding window pattern, learn Big O well enough to judge a constraint, and keep the Python cheat sheet open while you practise. If you have a few weeks, the 30-day study plan and the guide on how many problems to solve help you decide when you have done enough.