TCS NQT Coding Questions and Answers (with code)

Master the TCS NQT coding section with this practical guide. Learn the key question patterns, essential problem-solving techniques, and how to handle tricky input formats for success in the test.

TCS NQT Coding Questions and Answers (with code)

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.

Summarize this article with ChatGPT Get key takeaways & ask questions

Understanding the NQT Coding Section

Before diving into problems, understand the structure and common challenges of the NQT coding section.

Structure (The Integrated Test Pattern): TCS now uses a single 190-minute exam to decide all three job profiles. The test is strictly divided into:

Part A: Foundation (75 mins for basic aptitude/verbal)
Part B: Advanced (115 mins for advanced math, reasoning, and coding).

  • The Coding Section: You will specifically face 2 coding questions in the Advanced section, with a shared time limit of 90 minutes.
  • Roles & Difficulty: > * Ninja (~3.36 LPA): Heavily dependent on acing the Part A Foundation section and clearing basic cutoffs.
  • Digital (~7.0 LPA) & Prime (~9.0 - 12.0 LPA): You must conquer Part B. The two coding questions generally range from Moderate to Hard. Solving one fully and passing edge cases on the second secures a Digital interview. Solving both perfectly puts you in the Prime category.
  • Languages Allowed: You can use C, C++, Java, Python, or Perl. Pick the language you are most comfortable debugging under pressure.
  • The Strict Test Environment: The TCS iON compiler is notorious for being picky about input/output formats and whitespace. More importantly for 2026, physical rough paper is completely banned. You must use the on-screen rough pad and calculator. AI proctoring is incredibly strict, looking down at your desk will trigger warnings and potential disqualification.
Academy Pro

Java DSA Course

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.

2 projects
14 hrs
Data Structures Java Course

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 and second_largest to the smallest possible integer value.
  • Iterate through the array.
  • For each element, check:
    • If it's greater than largest, the current largest becomes the new second_largest, and this element becomes the new largest.
    • Else, if it's greater than second_largest (but not largest), it becomes the new second_largest.
  • Return second_largest.

Python Solution:

def find_second_largest(arr):
    if len(arr) < 2:
        return "Array size must be at least 2"

    # Use float('-inf') to avoid importing sys and handle all negatives
    largest = float('-inf')
    second_largest = float('-inf')

    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 == float('-inf'):
        return "No second largest element exists"
    else:
        return second_largest

# How to handle input in the TCS environment
try:
    n = int(input().strip())
    arr = []
    for _ in range(n):
        arr.append(int(input().strip()))
    
    result = find_second_largest(arr)
    print(result)

except ValueError:
    print("Invalid input")

Explanation:

  • Why this beats sorting: A beginner's instinct is to do list(set(arr)) , and then sort(), grabbing the second-to-last item. Do not do this. Sorting takes O(N log N) time. This single-pass solution takes O(N) time and O(1) space, which is mandatory to clear hidden test cases for large arrays.
  • We use float('-inf') instead of importing modules. It's cleaner, standard Python practice, and properly catches arrays filled entirely with negative integers (e.g., [-10, -40, -20]).
  • The input().strip() addition is crucial; TCS compilers often inject invisible trailing spaces that crash standard int() conversions.
Academy Pro

Python Programming Course

In this course, you will learn the fundamentals of Python: from basic syntax to mastering data structures, loops, and functions. You will also explore OOP concepts and objects to build robust programs.

11.5 Hrs
51 Coding Exercises
Start Free Trial

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 at i-1.
  • If they are different, it means you've found a new unique element. Copy it to arr[write_index] and increment write_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.

The Logic (Optimized for Digital/Prime Constraints):

While sorting the strings is the easiest method, it takes O(N log N) time. In the new TCS Advanced section, string lengths can be massive (e.g., 10^5 characters), and sorting will result in a Time Limit Exceeded (TLE) error. The optimal approach is O(N) time using a frequency counter (Hash Map/Dictionary).

  1. Check if the lengths are equal. If not, return False.
  2. Create an empty dictionary to count character frequencies.
  3. Loop through the first string, incrementing the count for each character.
  4. Loop through the second string, decrementing the count for each character. If a character is missing or its count drops below zero, they aren't anagrams.

Python Solution:

def are_anagrams(str1, str2):
    s1 = str1.replace(" ", "").lower()
    s2 = str2.replace(" ", "").lower()

    if len(s1) != len(s2):
        return False

    char_counts = {}
    
    # Build frequency map for first string
    for char in s1:
        char_counts[char] = char_counts.get(char, 0) + 1
        
    # Check frequencies against the second string
    for char in s2:
        if char not in char_counts or char_counts[char] == 0:
            return False
        char_counts[char] -= 1
        
    return True

# Input handling
try:
    string1 = input().strip()
    string2 = input().strip()

    if are_anagrams(string1, string2):
        print("Yes")
    else:
        print("No")
        
except Exception:
    print("Invalid input")

Explanation:

  • This approach operates in pure O(N) time, safely passing all massive string edge cases in the Prime category.
  • We use .get(char, 0) to avoid KeyError exceptions when building the dictionary, which is a common pitfall in high-pressure testing environments.

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.

  1. Handle the edge cases first: numbers less than or equal to 1 are not prime. 2 is the only even prime number.
  2. If the number is even (and not 2), it's not prime. Return false.
  3. 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.
  4. Iterate from 3 up to the square root of the number, incrementing by 2 (to check only odd divisors).
  5. If you find any number that divides it evenly, it's not prime.
  6. 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 an optimized way of checking up to the square root of N, executing in O(√N) time. It cleverly avoids floating-point calculations which can occasionally cause precision issues in strict testing environments.
  • 2026 Prime Role Warning: This O(√N) approach is perfect if they ask you to check one number. However, if the question asks you to "Find all prime numbers in a range up to 100,000" or gives you multiple queries, using this loop repeatedly will cause a Time Limit Exceeded (TLE) error. For range-based prime questions, you must learn and implement the Sieve of Eratosthenes algorithm, which generates primes in O(N log log N) time.

4. Advanced Topics (For Digital/Prime Roles)

If you are targeting the 7 LPA (Digital) or 9-12 LPA (Prime) packages, the 90-minute advanced coding section will push your limits. TCS has significantly raised the bar for Prime candidates, so basic arrays won't be enough.

Topics to master for 2026:

  • Advanced Data Structures: Stacks, Queues, Linked Lists, Trees, and basic Graph traversals (BFS/DFS) are highly tested.
  • Recursion & Backtracking: Generating subsets, permutations, or solving maze-based scenario questions.
  • Sorting & Searching: Beyond basic Bubble Sort, Insertion Sort, you must understand the logic and implementation of Merge Sort, Quick Sort, and Binary Search optimizations.
  • String Operations: Forward/backward shifting, matrix operations, and complex pattern matching.
  • Dynamic Programming (DP) & Greedy Algorithms: DP is no longer "very unlikely." For the Prime role, expect 1D and 2D dynamic programming questions (e.g., optimal path calculation, knapsack variations) and greedy approach problems. Time and space complexity constraints will be tight, so O(n^2) brute-force solutions will fail hidden test cases.

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 to False, so not [] is True.

Also Read:

Final Strategy: No Surprises

  • Understand the Scoring Game: There is no negative marking this year. Attempt every single question in the Foundation and Advanced sections.
  • Practice On-Screen Problem Solving: Since physical paper is banned, practice solving complex logic problems on your computer using a digital notepad before you write the actual code.
  • Master Input/Output: Write code specifically to handle different, vague input formats directly from stdin. Don't rely on auto-complete IDEs. This remains the #1 reason strong coders fail the NQT.
  • Time Management (90 Minutes for 2 Codes): You have a shared 90 minutes for the two coding questions. Secure the easier one completely first to lock in your Digital chances. If you get stuck on the harder one, implement a brute-force approach. Passing 5 out of 14 hidden test cases is vastly better than passing 0.
  • Language Choice: Use what you know best, but C++ is highly recommended by recent candidates for its performance speed and reliable behavior in the TCS iON environment, which easily clears tight time complexities where Python sometimes lags.
  • Don't Panic & Don't Look Down: Stay calm, keep your eyes on the screen to avoid AI warnings, and double-check your input handling if your logic seems flawless but the tests are failing.
Academy Pro

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.

Intermediate Level
9.17 hrs
Start Free Trial
Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top