Ad Code

NEW POST

6/recent/ticker-posts

TCS NQT Coding Questions 2026 – Most Asked with Solutions

https://ift.tt/wtn8YFz

 

TCS NQT Coding Questions 2026 – 6 Most Asked Problems with Java & Python Solutions

Introduction

If you’re preparing for TCS NQT 2026 and the coding section keeps you up at night, you’re not alone. Thousands of students struggle with the 2-question, 70-minute coding round that often decides whether you land the Ninja, Digital, or Prime profile. Based on actual questions asked in TCS NQT 2026 Shift 1 and Shift 2, this guide breaks down the 6 most frequently appearing coding problems with complete, tested solutions in both Java and Python. These aren’t random practice problems – these are the exact question patterns TCS repeatedly asks, making them high-priority for your preparation.

 

What You’ll Learn:

  • Complete solutions for 6 actual TCS NQT  2026 questions
  • Code in both Java and Python for flexibility
  • Detailed explanations of logic and approach
  • Edge case handling techniques
  • Time and space complexity analysis
  • Common mistakes to avoid

Let’s dive straight into the questions that can make or break your TCS placement.

Question 1: Count Positive, Negative, and Zero Numbers in Array

Asked in: TCS NQT 2026 Shift 1

Problem Statement

Given an array of integers, count how many numbers are positive (greater than 0), how many are negative (less than 0), and how many are exactly zero.

Input:

  • First line contains N (size of array)
  • Second line contains N space-separated integers

Output:

  • Three space-separated integers: count of positive, negative, and zero numbers

Example:

Input:
6
4 -2 0 7 -5 0

Output:
2 2 2

Explanation:

  • Positive numbers: 4, 7 (count = 2)
  • Negative numbers: -2, -5 (count = 2)
  • Zeros: 0, 0 (count = 2)

Solution Approach

The logic is straightforward: iterate through the array once, check each element’s sign, and increment the appropriate counter. This is a classic single-pass array traversal problem.

Algorithm:

  1. Initialize three counters: positive_count, negative_count, zero_count = 0
  2. Loop through each element in the array
  3. If element > 0, increment positive_count
  4. Else if element < 0, increment negative_count
  5. Else (element == 0), increment zero_count
  6. Print all three counts

Time Complexity: O(N) – single pass through array Space Complexity: O(1) – only three counter variables

Java Solution

import java.util.Scanner;

public class CountNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        // Read array size
        int n = sc.nextInt();
        
        // Initialize counters
        int positiveCount = 0;
        int negativeCount = 0;
        int zeroCount = 0;
        
        // Read array elements and count simultaneously
        for (int i = 0; i < n; i++) {
            int num = sc.nextInt();
            
            if (num > 0) {
                positiveCount++;
            } else if (num < 0) {
                negativeCount++;
            } else {
                zeroCount++;
            }
        }
        
        // Print results
        System.out.println(positiveCount + " " + negativeCount + " " + zeroCount);
        
        sc.close();
    }
}

🔗 Useful Links:

 

Python Solution

# Read input
n = int(input())
arr = list(map(int, input().split()))

# Initialize counters
positive_count = 0
negative_count = 0
zero_count = 0

# Count elements
for num in arr:
    if num > 0:
        positive_count += 1
    elif num < 0:
        negative_count += 1
    else:
        zero_count += 1

# Print results
print(positive_count, negative_count, zero_count)

Python One-Liner Alternative (Advanced)

n = int(input())
arr = list(map(int, input().split()))
print(sum(x > 0 for x in arr), sum(x < 0 for x in arr), sum(x == 0 for x in arr))

How the one-liner works:

  • sum(x > 0 for x in arr) counts True values (where True = 1, False = 0)
  • This is elegant but less readable for beginners

Common Mistakes to Avoid

❌ Mistake 1: Using >= instead of > for positive check (would count 0 as positive) ❌ Mistake 2: Forgetting the zero case entirely ❌ Mistake 3: Creating a separate array to store values (wastes memory)

Edge Cases to Test:

  • All positive: [1, 2, 3] → Output: 3 0 0
  • All negative: [-1, -2, -3] → Output: 0 3 0
  • All zeros: [0, 0, 0] → Output: 0 0 3
  • Single element: [5] → Output: 1 0 0

TCS_NQT_ Coding Questions: Click Here

TCS_NQT_ Aptitude & Coding Guide_: Click Here

TCS_HR_Interview_Guide : Click Here

Question 2: Reverse the Digits of a Number

Asked in: TCS NQT 2026 Shift 2

Problem Statement

Given an integer, reverse its digits. If the number is negative, the reversed number should also be negative.

Input:

  • Single integer N

Output:

  • Integer with reversed digits

Example:

Input: 12345
Output: 54321

Input: -678
Output: -876

Input: 120
Output: 21 (leading zeros removed)

Solution Approach

Extract digits one by one from the right (using modulo 10) and build the reversed number by multiplying the result by 10 and adding each digit.

Algorithm:

  1. Store original number’s sign (positive/negative)
  2. Work with absolute value
  3. Initialize reversed = 0
  4. While number > 0:
    • Extract last digit: digit = number % 10
    • Build reversed: reversed = reversed * 10 + digit
    • Remove last digit: number = number / 10
  5. Apply original sign to reversed number

Time Complexity: O(log N) – proportional to number of digits Space Complexity: O(1)

Java Solution

import java.util.Scanner;

public class ReverseNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int num = sc.nextInt();
        
        // Handle negative numbers
        int sign = (num < 0) ? -1 : 1;
        num = Math.abs(num);
        
        int reversed = 0;
        
        // Reverse digits
        while (num > 0) {
            int digit = num % 10;
            reversed = reversed * 10 + digit;
            num = num / 10;
        }
        
        // Apply original sign
        reversed = reversed * sign;
        
        System.out.println(reversed);
        
        sc.close();
    }
}

Python Solution

# Read input
num = int(input())

# Handle negative numbers
sign = -1 if num < 0 else 1
num = abs(num)

# Reverse digits
reversed_num = 0

while num > 0:
    digit = num % 10
    reversed_num = reversed_num * 10 + digit
    num = num // 10  # Integer division in Python

# Apply original sign
reversed_num = reversed_num * sign

print(reversed_num)

Python String Method Alternative

num = int(input())
sign = '-' if num < 0 else ''
reversed_num = sign + str(abs(num))[::-1]
print(int(reversed_num))

String Method Explanation:

  • str(abs(num)) converts to positive string
  • [::-1] reverses the string
  • Prepend sign if negative
  • Convert back to integer

Common Mistakes to Avoid

❌ Mistake 1: Not handling negative numbers (gets wrong sign) ❌ Mistake 2: Using / instead of // in Python (creates float) ❌ Mistake 3: Not considering trailing zeros (120 → 021 → should be 21) ❌ Mistake 4: Integer overflow for very large numbers (less common in Python)

Edge Cases to Test:

  • Single digit: 77
  • Negative: -123-321
  • Trailing zeros: 120021
  • Zero itself: 00

Question 3: Find Second Maximum Element in Array

Asked in: TCS NQT 2026 Shift 2

Problem Statement

Given an array of integers, find the second largest element. If all elements are the same or array has less than 2 elements, return -1.

Input:

  • First line contains N (size of array)
  • Second line contains N space-separated integers

Output:

  • Second maximum element or -1 if not possible

Example:

Input:
5
3 7 2 9 5

Output:
7

Input:
3
5 5 5

Output:
-1

Solution Approach

Use two variables to track the maximum and second maximum values in a single pass through the array.

Algorithm:

  1. Initialize max1 = -infinity, max2 = -infinity
  2. Iterate through array:
    • If current > max1:
      • max2 = max1 (old max becomes second max)
      • max1 = current (new maximum)
    • Else if current > max2 and current != max1:
      • max2 = current (new second max)
  3. Return max2 if it’s not -infinity, else return -1

Time Complexity: O(N) Space Complexity: O(1)

Java Solution

import java.util.Scanner;

public class SecondMaximum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        int[] arr = new int[n];
        
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        
        // Handle edge case
        if (n < 2) {
            System.out.println(-1);
            sc.close();
            return;
        }
        
        int max1 = Integer.MIN_VALUE;
        int max2 = Integer.MIN_VALUE;
        
        // Find max and second max
        for (int i = 0; i < n; i++) {
            if (arr[i] > max1) {
                max2 = max1;
                max1 = arr[i];
            } else if (arr[i] > max2 && arr[i] != max1) {
                max2 = arr[i];
            }
        }
        
        // Check if second max exists
        if (max2 == Integer.MIN_VALUE) {
            System.out.println(-1);
        } else {
            System.out.println(max2);
        }
        
        sc.close();
    }
}

Python Solution

# Read input
n = int(input())
arr = list(map(int, input().split()))

# Handle edge case
if n < 2:
    print(-1)
else:
    max1 = float('-inf')
    max2 = float('-inf')
    
    # Find max and second max
    for num in arr:
        if num > max1:
            max2 = max1
            max1 = num
        elif num > max2 and num != max1:
            max2 = num
    
    # Check if second max exists
    if max2 == float('-inf'):
        print(-1)
    else:
        print(max2)

Python Sorting Alternative (Less Efficient)

n = int(input())
arr = list(map(int, input().split()))

if n < 2:
    print(-1)
else:
    unique_arr = list(set(arr))  # Remove duplicates
    if len(unique_arr) < 2:
        print(-1)
    else:
        unique_arr.sort(reverse=True)
        print(unique_arr[1])

Note: Sorting method has O(N log N) time complexity, less efficient than single-pass O(N) approach.

Common Mistakes to Avoid

❌ Mistake 1: Not checking for duplicates (treating [5,5,3] → second max as 5 instead of 3) ❌ Mistake 2: Sorting and returning arr[-2] without removing duplicates ❌ Mistake 3: Not handling edge case where all elements are same ❌ Mistake 4: Not initializing with -infinity (fails for negative numbers)

Edge Cases to Test:

  • All same: [5, 5, 5]-1
  • Two elements: [3, 7]3
  • Negative numbers: [-5, -2, -8]-5
  • Single element: [9]-1

Question 4: Check if String is Palindrome

Asked in: TCS NQT  2026 Shift 2

Problem Statement

Given a string, determine whether it is a palindrome (reads the same forwards and backwards). Consider only alphanumeric characters and ignore case.

Input:

  • Single string

Output:

  • “YES” if palindrome, “NO” otherwise

Example:

Input: racecar
Output: YES

Input: hello
Output: NO

Input: A man a plan a canal Panama
Output: YES (ignoring spaces and case)

Solution Approach

Use two-pointer technique comparing characters from both ends moving inward.

Algorithm:

  1. Clean string: convert to lowercase, remove non-alphanumeric
  2. Use two pointers: left = 0, right = length – 1
  3. While left < right:
    • If chars don’t match, return NO
    • Move pointers inward
  4. If loop completes, return YES

Time Complexity: O(N) Space Complexity: O(1) for two-pointer, O(N) if creating cleaned string

Java Solution

import java.util.Scanner;

public class PalindromeCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        String str = sc.nextLine();
        
        // Clean string: remove non-alphanumeric, convert to lowercase
        str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        
        // Two-pointer approach
        int left = 0;
        int right = str.length() - 1;
        boolean isPalindrome = true;
        
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                isPalindrome = false;
                break;
            }
            left++;
            right--;
        }
        
        if (isPalindrome) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
        
        sc.close();
    }
}

Python Solution

# Read input
s = input()

# Clean string: keep only alphanumeric, convert to lowercase
cleaned = ''.join(char.lower() for char in s if char.isalnum())

# Two-pointer approach
left = 0
right = len(cleaned) - 1
is_palindrome = True

while left < right:
    if cleaned[left] != cleaned[right]:
        is_palindrome = False
        break
    left += 1
    right -= 1

print("YES" if is_palindrome else "NO")

Python Simple Alternative

s = input()
cleaned = ''.join(char.lower() for char in s if char.isalnum())

if cleaned == cleaned[::-1]:
    print("YES")
else:
    print("NO")

Common Mistakes to Avoid

❌ Mistake 1: Not handling case sensitivity (A ≠ a) ❌ Mistake 2: Not removing spaces/punctuation ❌ Mistake 3: Using == for strings in Java instead of .equals() ❌ Mistake 4: Creating new reversed string (wastes memory)

Edge Cases to Test:

  • Single char: "a"YES
  • Empty string: ""YES
  • With spaces: "race car"YES
  • Special chars: "A man, a plan!" → depends on problem (usually YES)

Question 5: Largest Sum of Consecutive Integers (Kadane’s Algorithm)

Asked in: TCS NQT  2026 Shift 1

Problem Statement

Given an array of integers (positive and negative), find the maximum sum of any contiguous subarray.

Input:

  • First line contains N
  • Second line contains N integers

Output:

  • Maximum sum of consecutive integers

Example:

Input:
6
-2 1 -3 4 -1 2

Output:
5

Explanation: Subarray [4, -1, 2] has the largest sum = 5

Solution Approach

Use Kadane’s Algorithm – maintain current sum and maximum sum seen so far.

Algorithm:

  1. Initialize current_sum = 0, max_sum = arr[0]
  2. For each element:
    • Add to current_sum
    • Update max_sum if current_sum > max_sum
    • If current_sum < 0, reset to 0
  3. Return max_sum

Time Complexity: O(N) Space Complexity: O(1)

Java Solution

import java.util.Scanner;

public class MaxSubarraySum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        int[] arr = new int[n];
        
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        
        // Kadane's Algorithm
        int currentSum = 0;
        int maxSum = Integer.MIN_VALUE;
        
        for (int i = 0; i < n; i++) {
            currentSum += arr[i];
            
            if (currentSum > maxSum) {
                maxSum = currentSum;
            }
            
            if (currentSum < 0) {
                currentSum = 0;
            }
        }
        
        System.out.println(maxSum);
        
        sc.close();
    }
}

Python Solution

# Read input
n = int(input())
arr = list(map(int, input().split()))

# Kadane's Algorithm
current_sum = 0
max_sum = float('-inf')

for num in arr:
    current_sum += num
    
    if current_sum > max_sum:
        max_sum = current_sum
    
    if current_sum < 0:
        current_sum = 0

print(max_sum)

Common Mistakes to Avoid

❌ Mistake 1: Not handling all negative arrays (would return 0 instead of largest negative) ❌ Mistake 2: Initializing max_sum = 0 (fails for all negative arrays) ❌ Mistake 3: Resetting current_sum before checking max_sum

Edge Cases to Test:

  • All negative: [-5, -2, -8]-2
  • All positive: [1, 2, 3]6
  • Mixed: [-2, 1, -3, 4, -1, 2, 1, -5, 4]6

Question 6: Print Star Pattern (Right-Angled Triangle)

Asked in: TCS NQT  2026 Shift 1

Problem Statement

Print a right-angled triangle pattern of stars with N rows.

Input:

  • Integer N (number of rows)

Output:

  • Star pattern

Example:

Input: 5

Output:
*
**
***
****
*****

Solution Approach

Use nested loops – outer loop for rows, inner loop for stars in each row.

Algorithm:

  1. For i from 1 to N:
    • For j from 1 to i:
      • Print star
    • Print newline

Time Complexity: O(N²) Space Complexity: O(1)

Java Solution

import java.util.Scanner;

public class StarPattern {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        
        // Print pattern
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        
        sc.close();
    }
}

Python Solution

# Read input
n = int(input())

# Print pattern
for i in range(1, n + 1):
    for j in range(i):
        print("*", end="")
    print()

Python One-Liner Alternative

n = int(input())
for i in range(1, n + 1):
    print("*" * i)

Common Pattern Variations

Inverted Right Triangle:

*****
****
***
**
*
for i in range(n, 0, -1):
    print("*" * i)

Pyramid Pattern:

    *
   ***
  *****
 *******
*********
for i in range(1, n + 1):
    print(" " * (n - i) + "*" * (2 * i - 1))

 

TCS Apply Link for 2024/25/26 : Click Here

Conclusion

These 6 TCS NQT coding questions from 2026 represent the core problem types you’ll encounter in your actual exam. The patterns repeat – array traversal, number manipulation, string operations, basic algorithms, and pattern printing form 80% of TCS NQT coding questions. Don’t chase hundreds of random problems. Master these fundamentals thoroughly, understand the logic deeply, and practice until you can solve them in your sleep.

Your TCS NQT 2026 success depends on consistent practice, not last-minute cramming. Set aside 2 hours daily for the next 4 weeks, solve these questions repeatedly in both Java and Python, and you’ll walk into the coding round with confidence. Remember, TCS doesn’t expect competitive programming wizards – they want engineers who can solve practical problems with clean, working code.

Download this guide, bookmark it, and revisit it every week during your preparation. Good luck cracking TCS NQT 2026!

The post TCS NQT Coding Questions 2026 – Most Asked with Solutions appeared first on placementdriveinsta.in.

Post a Comment

0 Comments