TCS NQT Coding Questions 2026: Pattern-Wise Solutions in Python and Java

TCS NQT coding questions grouped into six recurring patterns, from digit logic to array scans, each solved step by step in Python and Java with variants.

KnowledgeGate Team

Exam prep & CS education

19 Jul 20268 min read264 views

The TCS NQT coding section looks unpredictable until you place questions from past cycles side by side. Then the fear evaporates: most of them are a small set of patterns wearing different clothes. Learn each pattern once, drill its variants, and you walk into the test having effectively seen the paper before.

Six patterns cover almost everything the section sets: digit logic, string transforms, array scans, GCD and primes, series and recursion, and the sort-first family. Each has one core move, and once you can write that move from a blank editor in Python or Java, its variants stop being new problems. For the full section-by-section picture of the exam, start with The TCS NQT Exam Structure, Explained Section by Section.

TCS NQT coding section: where it sits and what to confirm

Under the NQT's Integrated Test Pattern, the paper splits into a Foundation section (Numerical, Verbal and Reasoning Ability) and an Advanced section (advanced quantitative ability, advanced reasoning and coding). Coding sits in the Advanced section, which is what separates aspirants targeting the higher TCS Digital and Prime roles from a plain Ninja attempt.

The number of coding questions, the time allotted, and the permitted languages are official specifics that can change between cycles, so confirm them on the official TCS NQT hiring page before your attempt. None of that changes the patterns, and the logic is identical whether you submit in Python or Java. Write in whichever permitted language you code fastest.

The six patterns, each with the anchor question to learn first and the variants it spawns:

Pattern

Anchor question

Typical variants

Digit logic

Reverse a number, palindrome check

Armstrong number, digit sum, digit count

String transforms

Character frequency count

Remove duplicates, anagram check, reverse words

Array scans

Second largest without sorting

Missing number, pair with given sum, rotation

GCD, LCM and primes

Euclid's GCD, primality test

Primes in a range, co-primes, factorisation

Series and recursion

Fibonacci series

Factorial, series sums, pattern printing

Sort first, then answer

Kth smallest element

Minimum-difference pair, merge sorted arrays

Pattern 1: digit logic (reverse, palindrome, Armstrong)

The core move: peel digits off a number with % 10 and integer division by 10. Every digit question is this one loop with a different accumulator.

Anchor: reverse a number and check if it is a palindrome.

n = int(input())
original, rev = n, 0
while n > 0:
    rev = rev * 10 + n % 10
    n //= 10
print("Palindrome" if rev == original else "Not palindrome")
int n = sc.nextInt(), original = n, rev = 0;
while (n > 0) {
    rev = rev * 10 + n % 10;
    n /= 10;
}
System.out.println(rev == original ? "Palindrome" : "Not palindrome");

Run the Python version on 1221 and the loop peels one digit per turn:

Turn

n at start

n % 10

rev after

n after

1

1221

1

1

122

2

122

2

12

12

3

12

2

122

1

4

1

1

1221

0

n reaches 0, the loop stops, and rev holds 1221, which equals the original, so the program prints Palindrome. Feed it 1234 and rev ends at 4321, no match, so it prints Not palindrome.

Drill the variants by changing only the line inside the loop: add n % 10 for a digit sum, count iterations for digit count, raise each digit to the power of the number of digits and compare the total with the original for an Armstrong number. Check that Armstrong variant on 153: it has three digits, so cube each one and add, 1 + 125 + 27 = 153, which matches. Try 154 and you get 1 + 125 + 64 = 190, which does not.

Pattern 2: string transforms (frequency, duplicates, reversal)

The core move: walk the string once and build your answer as you go, usually with a frequency map or array.

Anchor: print the frequency of every character.

s = input().strip()
freq = {}
for ch in s:
    freq[ch] = freq.get(ch, 0) + 1
for ch, count in freq.items():
    print(ch, count)
String s = sc.next();
int[] freq = new int[256];
for (char ch : s.toCharArray()) freq[ch]++;
for (int i = 0; i < 256; i++)
    if (freq[i] > 0) System.out.println((char) i + " " + freq[i]);

The same frequency structure answers the first non-repeating character (first index with count 1), duplicate removal (print only on first sighting), and the anagram check (two frequency arrays must match). Reversing word order is the one outlier: split on spaces, join in reverse.

Pattern 3: array scan questions (one pass, small state)

The core move: a single pass while tracking a small amount of state, such as the largest and second largest seen so far. Sorting solves many of these too, but the single pass costs O(n) against sorting's O(n log n), and it leaves the input order intact for whatever the question asks next.

Anchor: second largest element without sorting.

a = list(map(int, input().split()))
first = second = float("-inf")
for x in a:
    if x > first:
        second, first = first, x
    elif first > x > second:
        second = x
print(second)
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : a) {
    if (x > first) { second = first; first = x; }
    else if (x > second && x < first) second = x;
}
System.out.println(second);

Trace it on 12 35 1 10 34 1. After the first two values the pair (first, second) is (35, 12). 1 and 10 are too small to displace either. 34 is below 35 but above 12, so it becomes the new second. The trailing 1 changes nothing, and the loop prints 34 after one pass and two variables.

Variants: the missing number from 1 to n (expected sum n(n+1)/2 minus actual sum), counting evens and odds, finding a pair with a given sum, and rotating an array left by one position.

Pattern 4: GCD, LCM and prime checks

Two tools cover this whole family: Euclid's algorithm for GCD, and trial division up to the square root for primality.

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def is_prime(n):
    if n < 2:
        return False
    i = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += 1
    return True
static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }

static boolean isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; (long) i * i <= n; i++)
        if (n % i == 0) return false;
    return true;
}

LCM comes free: a / gcd(a, b) * b (divide first to avoid overflow in Java). Variants: print all primes in a range, check whether two numbers are co-prime (GCD equals 1), and prime factorisation by repeated division.

Pattern 5: series, factorial and Fibonacci

The core move: build the series iteratively with two or three rolling variables. Recursion is elegant but iteration is safer under test pressure.

Anchor: print the first n Fibonacci numbers.

n = int(input())
a, b = 0, 1
for _ in range(n):
    print(a, end=" ")
    a, b = b, a + b
long a = 0, b = 1;
for (int i = 0; i < n; i++) {
    System.out.print(a + " ");
    long t = a + b; a = b; b = t;
}

One trap to respect: growth. Factorials and Fibonacci numbers overflow int quickly, so use long in Java; Python integers are unbounded, which is one reason many aspirants submit in Python. Variants: factorial, sum of series like 1 + 1/2 + 1/3 + ... + 1/n, and the star or number pattern-printing questions, which are the same discipline applied to nested loops.

Pattern 6: sort first, then answer

The core move: many questions that look clever become one line after you sort. Recognising this pattern is mostly about not overthinking.

Anchor: the kth smallest element.

a = sorted(map(int, input().split()))
k = int(input())
print(a[k - 1])
Arrays.sort(a);
System.out.println(a[k - 1]);

Variants: the pair with minimum difference (sort, then compare neighbours), merging two sorted arrays, and checking whether an array is already sorted (one comparison per neighbour, no sort needed, but the mindset is the same).

How to drill the six patterns

Knowing the patterns is not the same as producing working code at speed. A drill routine that works:

  1. Code each anchor question from a blank editor, no references, until it compiles and runs first time. That is one evening per pattern.

  2. Then do three or four variants per pattern under a self-imposed time limit. The variant is where learning happens, because it forces you to see the pattern under new wording.

  3. Finish with mixed timed sets, so pattern recognition itself is tested. Variants of previously asked questions beat random new ones; the reasoning in Why Solving PYQs Beats Buying Another Question Bank applies to coding rounds exactly as it does to MCQs.

Two weeks of this, an hour a day, covers all six patterns with variants. It is a small, finite amount of work for the section that decides whether your NQT score reaches Digital and Prime territory. More placement guides live in our Placement Preparation section.

Your next step

Patterns give you the skeleton; timed practice on real, NQT-level questions puts flesh on it. The TCS NQT 2026 Test Series is built for exactly this stage: full-length mocks following the Integrated Test Pattern across the Foundation and Advanced sections, dedicated coding tests with step-by-step solutions, and an all-India ranking so you know where you stand among the 2024, 2025 and 2026 batches. If coding is already your strong suit and aptitude is what worries you, start instead with our 30-day aptitude practice routine.

The short version: six patterns, one anchor solution each, three variants per pattern, then timed mocks. Confirm the current section details on the official TCS NQT page on tcs.com, and spend your remaining weeks writing code, not watching more videos.