Want to crack the TCS NQT coding section? It’s a guide to help you. We’ll cover the patterns, the types of questions they throw at you, and how to solve them without unnecessary complexity.
The coding section is where they separate the people who can talk about code from the people who can write it. Your goal is to pass the test cases. Let’s get straight to it.
Understanding the NQT Coding Section
Before diving into problems, understand the issues.
- Structure: Typically, you’ll get two, sometimes three, coding questions.
- Roles:
- Solve the first (easier) one correctly -> Good chance for a Ninja interview.
- Solve both -> You’re in the running for a Digital or Prime interview.
- Difficulty: It ranges. The first question is usually straightforward, based on fundamentals. The second one is a step up, often involving more complex logic or basic data structures and algorithms (DSA).
- Languages Allowed: You can use C, C++, Java, Python, or Perl. Pick the one you’re fastest with. Python is popular for its speed of writing.
- The Infamous Compiler: The TCS test environment is notorious. It’s not like your local VS Code or a modern IDE like LeetCode’s. It can be picky about input/output and sometimes slow. People on Reddit constantly complain about its quirks, especially with Python indentation and input handling. Be prepared for this.
Learn Data Structures & Algorithms (DSA) in Java to excel in coding interviews and software development. Master linked lists, trees, graphs, heaps, hashing, sorting, and more while building efficient, optimized solutions.
The Most Important Skill: Handling Input
This is very important. More people fail because they can’t read the input correctly than because their logic is wrong. The compiler is strict, and the problem descriptions can be vague about the input format.
The Rule: Assume the simplest input format unless specified.
- If they need a list of numbers, they’ll likely provide N on the first line, followed by N numbers on subsequent lines, each on a new line.
- Don’t try to get fancy with
split()
or parsing comma-separated strings unless the problem explicitly says so. - Practice reading various input types: a single integer, a line of space-separated integers, an integer N followed by N lines of input, etc. This is a common failure point.
Pro Tip for Python Users: The compiler’s handling of tabs versus spaces for indentation is a known issue. Use spaces for indentation to be safe. Some candidates report that tabs simply do not work correctly.
Core Topics & Solved Questions
Here’s a breakdown of the question types you will face. We’ll go through each with examples. Focus on the logic. The implementation is just a tool.
1. Array-Based Questions
Arrays are the bread and butter of the NQT. You are almost guaranteed to get an array question. They test your ability to manipulate a list of numbers.
Common Array Problems:
- Finding the second largest/smallest element.
- Removing duplicates from a sorted or unsorted array.
- Rotating an array by ‘k’ elements.
- Finding a missing number in a sequence.
- Sorting an array of 0s, 1s, and 2s.
Question 1: Find the Second Largest Number in an Array
Problem: Given an array of integers, find the second largest element.
The Logic:
Don’t overthink this. You don’t need to sort the whole array; that’s inefficient. You only need two variables: largest
and second_largest
.
- Initialize
largest
andsecond_largest
to the smallest possible integer value. - Iterate through the array.
- For each element, check:
- If it’s greater than
largest
, the currentlargest
becomes the newsecond_largest
, and this element becomes the newlargest
. - Else, if it’s greater than
second_largest
(but notlargest
), it becomes the newsecond_largest
.
- If it’s greater than
- Return
second_largest
.
Python Solution:
import sys
def find_second_largest(arr):
if len(arr) < 2:
return "Array size must be at least 2"
largest = -sys.maxsize
second_largest = -sys.maxsize
for num in arr:
if num > largest:
second_largest = largest
largest = num
elif num > second_largest and num != largest:
second_largest = num
if second_largest == -sys.maxsize:
return "No second largest element exists"
else:
return second_largest
# How to handle input in the TCS environment
try:
n = int(input())
arr = []
for _ in range(n):
arr.append(int(input()))
result = find_second_largest(arr)
print(result)
except ValueError:
print("Invalid input")
Explanation:
- We use
-sys.maxsize
to handle negative numbers correctly. - The
and num != largest
check handles duplicate largest elements. - The final check sees if
second_largest
was ever updated. If not, it means all elements were the same.
Question 2: Remove Duplicates from a Sorted Array
Problem: Given a sorted array, remove the duplicates in-place such that each element appears only once. Return the new length of the array.
The Logic:
This is a classic two-pointer problem. Since the array is sorted, all duplicate elements will be adjacent.
- Use one pointer (
write_index
) to keep track of the position where the next unique element should be placed. Initialize it to 1 (since the first element is always unique). - Use a second pointer (
i
) to iterate through the array from the second element (i = 1
). - Compare the element at
i
with the element ati-1
. - If they are different, it means you’ve found a new unique element. Copy it to
arr[write_index]
and incrementwrite_index
. - If they are the same, do nothing but continue iterating with
i
. - The final value of
write_index
is your new length.
Python Solution:
def remove_duplicates(arr):
if not arr:
return 0
write_index = 1
for i in range(1, len(arr)):
if arr[i] != arr[i-1]:
arr[write_index] = arr[i]
write_index += 1
return write_index
# Example Input Handling
try:
# Assuming input is space-separated integers on one line
# Note: This input style might vary. Adapt as needed.
input_line = input()
arr = list(map(int, input_line.split()))
new_length = remove_duplicates(arr)
# Printing the modified array up to the new length
for i in range(new_length):
print(arr[i], end=" ")
print() # for a newline at the end
except (ValueError, IndexError):
print("Invalid input format")
Explanation:
- This approach is efficient (O(n) time complexity) because it modifies the array in a single pass.
- It works “in-place,” meaning it doesn’t use extra memory for another array, which is often a requirement.
2. String Manipulation Questions
String questions are also very common. They test your understanding of characters, substrings, and basic string algorithms.
Common String Problems:
- Check if a string is a palindrome.
- Count vowels and consonants.
- Find duplicate characters.
- Check if two strings are anagrams.
- Reverse words in a sentence.
Question 3: Check if Two Strings are Anagrams
Problem: Given two strings, determine if they are anagrams of each other. An anagram is a word formed by rearranging the letters of another, like “listen” and “silent”.
The Logic:
The simplest, most direct approach is to sort both strings. If the sorted versions are identical, they are anagrams.
- First, check if the lengths of the two strings are equal. If not, they can’t be anagrams.
- Convert both strings into character arrays (or lists in Python).
- Sort both arrays.
- Join the sorted characters back into strings.
- Compare the two sorted strings. If they are equal, the original strings are anagrams.
Python Solution:
def are_anagrams(str1, str2):
# Clean the strings: remove spaces and convert to a consistent case
s1 = str1.replace(" ", "").lower()
s2 = str2.replace(" ", "").lower()
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2)
# Input handling
try:
string1 = input()
string2 = input()
if are_anagrams(string1, string2):
print("Yes")
else:
print("No")
except Exception:
print("Invalid input")
Explanation:
sorted(s1)
returns a sorted list of characters.['e', 'i', 'l', 'n', 's', 't']
.- Comparing two lists
['a', 'b'] == ['a', 'b']
works directly in Python. - This is a clean, readable, and generally efficient solution for typical NQT constraints.
3. Number Theory and Mathematical Problems
These questions involve logic based on mathematical concepts. They are less about complex data structures and more about your problem-solving logic.
Common Number Theory Problems:
- Check if a number is prime.
- Find the GCD (Greatest Common Divisor) of two numbers.
- Check for Armstrong or Palindrome numbers.
- Generate Fibonacci series.
- Convert between number systems (e.g., decimal to binary).
Question 4: Check for a Prime Number
Problem: Given an integer, determine if it is a prime number.
The Logic:
A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.
- Handle the edge cases first: numbers less than or equal to 1 are not prime. 2 is the only even prime number.
- If the number is even (and not 2), it’s not prime. Return false.
- For odd numbers, you don’t need to check for divisibility all the way up to the number itself. You only need to check up to its square root.
- Iterate from 3 up to the square root of the number, incrementing by 2 (to check only odd divisors).
- If you find any number that divides it evenly, it’s not prime.
- If the loop finishes without finding any divisors, the number is prime.
Python Solution:
import math
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# Iterate from 3 up to the square root of n, only checking odd numbers
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
# Input handling
try:
num = int(input())
if is_prime(num):
print("Prime")
else:
print("Not Prime")
except ValueError:
print("Invalid input. Please enter an integer.")
Explanation:
- The
i * i <= n
condition is a more efficient way of writingi <= math.sqrt(n)
. It avoids floating-point calculations. - This logic is optimized. A brute-force check up to
n/2
orn
might be too slow and could fail time complexity test cases in the exam.
4. Advanced Topics (For Digital/Prime Roles)
If you are aiming for the higher-paying Digital or Prime roles, you need to be prepared for more than the basics. These questions may touch upon fundamental Data Structures and Algorithms.
Topics to be aware of:
- Recursion: Problems like finding factorials or generating subsets.
- Sorting Algorithms: Know how Bubble Sort, Insertion Sort, and Merge Sort work conceptually. You might not need to implement Merge Sort from scratch, but understanding the logic helps.
- Basic Data Structures:
- Stacks: Useful for problems like checking for balanced parentheses.
- Queues: Basic implementation and use cases.
- Linked Lists: Reversing a linked list is a classic problem.
- Greedy Algorithms: Simple problems where making the locally optimal choice leads to a global solution.
- Dynamic Programming (DP): Very unlikely, but the most basic DP problems (like the Fibonacci sequence) can sometimes appear disguised as simpler problems.
Also Read: Linked List Interview Questions and Answers
Question 5: Balanced Parentheses
Problem: Given a string containing just the characters (
, )
, {
, }
, [
and ]
, determine if the input string is valid. An input string is valid if open brackets are closed by the same type of brackets and in the correct order.
The Logic:
This is the classic use case for a stack.
- Create a mapping of opening brackets to their corresponding closing brackets. e.g.,
{'(': ')'}
. - Initialize an empty stack (a list in Python can act as a stack).
- Iterate through the input string character by character.
- If the character is an opening bracket (
(
,{
,[
), push it onto the stack. - If the character is a closing bracket (
)
,}
,]
):- Check if the stack is empty. If it is, there’s no matching opening bracket, so the string is invalid.
- Pop the top element from the stack.
- Check if the current closing bracket is the correct match for the popped opening bracket (using your map). If not, it’s invalid.
- After the loop finishes, check if the stack is empty. If it is, all brackets were matched correctly. If it’s not empty, it means there are unclosed opening brackets, so it’s invalid.
Python Solution:
def is_balanced(s):
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping: # It's a closing bracket
# Pop the top element from the stack if it's not empty, otherwise assign a dummy value
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else: # It's an opening bracket
stack.append(char)
# The string is balanced only if the stack is empty at the end
return not stack
# Input handling
try:
expression = input()
if is_balanced(expression):
print("Balanced")
else:
print("Not Balanced")
except Exception:
print("An error occurred.")
Explanation:
- The stack perfectly models the “last-in, first-out” nature of nested brackets. The last opening bracket you see must be the first one you close.
- The final
return not stack
is a concise way to check if the stack is empty. An empty list evaluates toFalse
, sonot []
isTrue
.
Also Read:
- TCS Normal Interview Questions and Answers
- TCS Aptitude Questions and Answers
- Accenture Coding Questions and Solutions (with code)
Final Strategy: No Surprises
- Master the Basics: Don’t waste time on obscure algorithms. Get extremely good at solving problems with arrays, strings, and basic math. This is enough for the Ninja role and is the foundation for Digital/Prime.
- Practice Input/Output: Write code specifically to handle different input formats. Don’t rely on a fancy IDE to do it for you. This is a known trap in the NQT.
- Time Management: The first question is your ticket to an interview. Secure it. Don’t get bogged down. If you’re stuck for more than 5-10 minutes on a complex approach, try a simpler, brute-force solution. A partially correct solution (passing some test cases) is better than nothing.
- Language Choice: Use what you know best, but be aware of language-specific pitfalls in the TCS environment (like Python’s indentation issues). Many recommend C++ for its performance and reliable behavior in these test environments.
- Don’t Panic: People who know the material fail because they panic. If your code doesn’t work, debug it calmly. Read the problem statement again. Check your input handling. The issue is often simpler than you think.
C++ Data Structures and Algorithms Course Course
Master DSA (Data Structures and Algorithms) with C++. Build coding skills in arrays, trees, graphs, heaps, sorting, searching, hashing, and algorithm analysis for interviews.