TCS Coding Questions
About TCS National Qualifier Test (NQT)
TCS National Qualifier Test (NQT) is a standardized assessment conducted by Tata Consultancy Services for recruiting fresh graduates from various educational institutions across India. It serves as the initial screening process for entry-level roles at TCS and offers multiple career opportunities to candidates.
Test Pattern
Sections | Duration (mins) |
---|---|
Part A - Foundation Section | 75 |
Numerical Ability | 25 |
Verbal Ability | 25 |
Reasoning Ability | 25 |
Part B - Advanced Section | 115 |
Advanced Quantitative & Reasoning Ability | 25 |
Advanced Coding | 90 |
Total Duration | 190 |
Career Tracks Based on Performance
Based on test performance, candidates qualify for one of the following hiring categories:
- Prime : Highest tier offering - requires excellent performance in both Foundation and Advanced sections
- Digital : Advanced technical role - Advanced section is mandatory for consideration
- Ninja : Standard developer role - can qualify with strong Foundation section performance
Application Process
- Log in to the TCS NextStep Portal
- Register and Apply for the Drive
- Select In-center mode of test and choose preferred test centers
- Track application status - should reflect as "Applied for Drive"
Interview Process
After clearing the NQT, candidates undergo a rigorous interview process that includes programming questions. The complexity varies based on the role:
- Prime : Most challenging technical questions and system design concepts
- Digital : Advanced DSA topics and problem-solving skills
- Ninja : Fundamental programming concepts and basic algorithms
MOST COMMONLY GIVEN PROGRAMMING QUESTIONS IN INTERVIEW ROUND IN TCS
Check for Leap Year
function isLeapYear(year) {
if (year % 400 === 0) return true;
if (year % 100 === 0) return false;
return year % 4 === 0;
}
// Example usage
console.log(isLeapYear(2020)); // true
console.log(isLeapYear(2100)); // false
console.log(isLeapYear(2000)); // true
Fibonacci Sequence
function generateFibonacci(n) {
const fibonacci = [0, 1];
for (let i = 2; i < n; i++) {
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
}
return fibonacci.slice(0, n);
}
// Example usage
console.log(generateFibonacci(10)); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Prime Number Check
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
let i = 5;
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) return false;
i += 6;
}
return true;
}
// Example usage
console.log(isPrime(11)); // true
console.log(isPrime(15)); // false
Sum of Natural Numbers
function sumOfNaturalNumbers(n) {
return (n * (n + 1)) / 2;
}
// Example usage
console.log(sumOfNaturalNumbers(10)); // 55
Array Rotation
function rotateArray(arr, k) {
const n = arr.length;
k = k % n;
const rotated = [...arr.slice(n - k), ...arr.slice(0, n - k)];
return rotated;
}
// Example usage
console.log(rotateArray([1, 2, 3, 4, 5], 2)); // [4, 5, 1, 2, 3]
Find Maximum and Minimum in an Array
function findMaxMin(arr) {
if (arr.length === 0) return { max: undefined, min: undefined };
let max = arr[0];
let min = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
return { max, min };
}
// Example usage
console.log(findMaxMin([3, 5, 1, 9, 2])); // { max: 9, min: 1 }
Palindrome String Check
function isPalindromeString(str) {
const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleanStr === cleanStr.split('').reverse().join('');
}
// Example usage
console.log(isPalindromeString("A man, a plan, a canal: Panama")); // true
console.log(isPalindromeString("hello")); // false
Binary Search Implementation
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Target not found
}
// Example usage
console.log(binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 7)); // 6
console.log(binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11)); // -1
Armstrong Number Check
function isArmstrongNumber(num) {
const digits = num.toString().split('');
const power = digits.length;
const sum = digits.reduce((acc, digit) => {
return acc + Math.pow(parseInt(digit), power);
}, 0);
return sum === num;
}
// Example usage
console.log(isArmstrongNumber(153)); // true (1^3 + 5^3 + 3^3 = 153)
console.log(isArmstrongNumber(370)); // true (3^3 + 7^3 + 0^3 = 370)
console.log(isArmstrongNumber(123)); // false
Reverse a String
function reverseString(str) {
return str.split('').reverse().join('');
}
// Example usage
console.log(reverseString("hello")); // "olleh"
TCS Digital Questions
Two Sum Problem
function twoSum(nums, target) {
const numToIndex = {};
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (complement in numToIndex) {
return [numToIndex[complement], i];
}
numToIndex[nums[i]] = i;
}
return [-1, -1]; // No solution found
}
// Example usage
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
Find Duplicate in an Array
function findDuplicate(nums) {
// Floyd's Tortoise and Hare (Cycle Detection)
let slow = nums[0];
let fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow !== fast);
slow = nums[0];
while (slow !== fast) {
slow = nums[slow];
fast = nums[fast];
}
return fast;
}
// Example usage
console.log(findDuplicate([1, 3, 4, 2, 2])); // 2
Longest Substring Without Repeating Characters
function lengthOfLongestSubstring(s) {
const charMap = new Map();
let maxLength = 0;
let start = 0;
for (let end = 0; end < s.length; end++) {
const currentChar = s[end];
if (charMap.has(currentChar)) {
start = Math.max(charMap.get(currentChar) + 1, start);
}
charMap.set(currentChar, end);
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}
// Example usage
console.log(lengthOfLongestSubstring("abcabcbb")); // 3
console.log(lengthOfLongestSubstring("bbbbb")); // 1
console.log(lengthOfLongestSubstring("pwwkew")); // 3
Implement Merge Sort
function mergeSort(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
}
function merge(left, right) {
const result = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
return [...result, ...left.slice(leftIndex), ...right.slice(rightIndex)];
}
// Example usage
console.log(mergeSort([5, 3, 8, 4, 2, 1, 6])); // [1, 2, 3, 4, 5, 6, 8]
Kth Largest Element in an Array
function findKthLargest(nums, k) {
// Quick select algorithm
return quickSelect(nums, 0, nums.length - 1, nums.length - k);
}
function quickSelect(nums, left, right, kSmallest) {
if (left === right) return nums[left];
const pivotIndex = partition(nums, left, right);
if (pivotIndex === kSmallest) {
return nums[pivotIndex];
} else if (pivotIndex < kSmallest) {
return quickSelect(nums, pivotIndex + 1, right, kSmallest);
} else {
return quickSelect(nums, left, pivotIndex - 1, kSmallest);
}
}
function partition(nums, left, right) {
const pivot = nums[right];
let i = left;
for (let j = left; j < right; j++) {
if (nums[j] <= pivot) {
[nums[i], nums[j]] = [nums[j], nums[i]];
i++;
}
}
[nums[i], nums[right]] = [nums[right], nums[i]];
return i;
}
// Example usage
console.log(findKthLargest([3, 2, 1, 5, 6, 4], 2)); // 5
Palindrome Number
function isPalindromeNumber(x) {
if (x < 0) return false;
const str = x.toString();
const reverseStr = str.split('').reverse().join('');
return str === reverseStr;
}
// Example usage
console.log(isPalindromeNumber(121)); // true
console.log(isPalindromeNumber(-121)); // false
console.log(isPalindromeNumber(10)); // false
Move Zeros in an Array
function moveZeroes(nums) {
let nonZeroIndex = 0;
// Move all non-zero elements to the front
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[nonZeroIndex] = nums[i];
nonZeroIndex++;
}
}
// Fill the rest with zeros
for (let i = nonZeroIndex; i < nums.length; i++) {
nums[i] = 0;
}
return nums;
}
// Example usage
console.log(moveZeroes([0, 1, 0, 3, 12])); // [1, 3, 12, 0, 0]
Maximum Subarray Problem (Kadane's Algorithm)
function maxSubArray(nums) {
let maxSum = nums[0];
let currentSum = nums[0];
for (let i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
// Example usage
console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6
Valid Parentheses
function isValidParentheses(s) {
const stack = [];
const brackets = {
'(': ')',
'[': ']',
'{': '}'
};
for (let char of s) {
if (char in brackets) {
stack.push(char);
} else {
const lastBracket = stack.pop();
if (brackets[lastBracket] !== char) {
return false;
}
}
}
return stack.length === 0;
}
// Example usage
console.log(isValidParentheses("()")); // true
console.log(isValidParentheses("()[]{}")); // true
console.log(isValidParentheses("(]")); // false
Climbing Stairs Problem
function climbStairs(n) {
if (n <= 2) return n;
let oneStepBefore = 2;
let twoStepsBefore = 1;
let ways = 0;
for (let i = 3; i <= n; i++) {
ways = oneStepBefore + twoStepsBefore;
twoStepsBefore = oneStepBefore;
oneStepBefore = ways;
}
return ways;
}
// Example usage
console.log(climbStairs(3)); // 3
console.log(climbStairs(5)); // 8
TCS Ninja Questions
Check if Array is Sorted
function isSorted(arr) {
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[i-1]) {
return false;
}
}
return true;
}
// Example usage
console.log(isSorted([1, 2, 3, 4, 5])); // true
console.log(isSorted([1, 2, 4, 3, 5])); // false
Bubble Sort Algorithm
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n; i++) {
let swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
swapped = true;
}
}
// If no swapping occurred in this pass, array is sorted
if (!swapped) break;
}
return arr;
}
// Example usage
console.log(bubbleSort([5, 3, 8, 4, 2])); // [2, 3, 4, 5, 8]
Sum of Array Elements
function sumArray(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}
// Example usage
console.log(sumArray([1, 2, 3, 4, 5])); // 15
Check for Prime Numbers in a Range
function primesInRange(start, end) {
const primes = [];
for (let num = start; num <= end; num++) {
if (isPrime(num)) {
primes.push(num);
}
}
return primes;
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
let i = 5;
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) return false;
i += 6;
}
return true;
}
}
// Example usage
console.log(primesInRange(10, 30)); // [11, 13, 17, 19, 23, 29]
Count the Frequency of Characters in a String
function characterFrequency(str) {
const frequency = {};
for (let char of str) {
frequency[char] = (frequency[char] || 0) + 1;
}
return frequency;
}
// Example usage
console.log(characterFrequency("hello")); // { h: 1, e: 1, l: 2, o: 1 }
Find the Second Largest Element in an Array
function findSecondLargest(arr) {
if (arr.length < 2) return -1;
let largest = arr[0];
let secondLargest = -Infinity;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] < largest && arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
return secondLargest === -Infinity ? -1 : secondLargest;
}
// Example usage
console.log(findSecondLargest([12, 35, 1, 10, 34, 1])); // 34
Perfect Number Check
function isPerfectNumber(num) {
if (num <= 1) return false;
let sum = 1; // Start with 1 as every number is divisible by 1
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
sum += i;
if (i !== num / i) {
sum += num / i;
}
}
}
return sum === num;
}
// Example usage
console.log(isPerfectNumber(6)); // true (6 = 1 + 2 + 3)
console.log(isPerfectNumber(28)); // true (28 = 1 + 2 + 4 + 7 + 14)
console.log(isPerfectNumber(12)); // false
Factorial of a Number
function factorial(n) {
if (n < 0) return null;
if (n <= 1) return 1;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// Example usage
console.log(factorial(5)); // 120
Sort an Array of 0s, 1s, and 2s (Dutch National Flag Problem)
function sortColors(nums) {
let low = 0;
let mid = 0;
let high = nums.length - 1;
while (mid <= high) {
if (nums[mid] === 0) {
[nums[low], nums[mid]] = [nums[mid], nums[low]];
low++;
mid++;
} else if (nums[mid] === 1) {
mid++;
} else if (nums[mid] === 2) {
[nums[mid], nums[high]] = [nums[high], nums[mid]];
high--;
}
}
return nums;
}
// Example usage
console.log(sortColors([2, 0, 2, 1, 1, 0])); // [0, 0, 1, 1, 2, 2]
DSA Questions by Role
NQT DSA Questions
- Reverse a Linked List
- Fibonacci Series Using Recursion
- Check if a String is Palindrome
- Find the Middle of a Linked List
- Bubble Sort Algorithm
- Remove Duplicates from a Sorted Linked List
- Maximum Sum Subarray (Kadane's Algorithm)
- Check if a Tree is a Binary Search Tree
- Binary Search
- Insertion Sort Algorithm
- Find the nth Node from the End of a Linked List
- Detect Loop in a Linked List
- Merge Two Sorted Arrays
- Balanced Parentheses
- Intersection of Two Linked Lists
- Sorting a Stack Using Recursion
- Find the Minimum Element in a Stack
- Reverse a String Using Stack
- Check for Anagrams
- Move Zeroes to the End of Array
Digital DSA Questions
- Two Sum Problem
- Find the Longest Palindromic Substring
- Merge Intervals
- Quick Sort Algorithm
- Find the Kth Largest Element in an Array
- Trapping Rain Water
- Longest Common Subsequence
- Top K Frequent Elements
- Binary Tree Level Order Traversal
- Longest Increasing Subsequence
- Rotate Matrix by 90 Degrees
- Nth Fibonacci Number Using Dynamic Programming
- Flatten a Multilevel Doubly Linked List
- Find the First Missing Positive
- Zigzag Level Order Traversal of a Binary Tree
- Find the Lowest Common Ancestor in a Binary Tree
- Detect Cycle in a Directed Graph
- Median of Two Sorted Arrays
- Merge K Sorted Linked Lists
- Coin Change Problem
Ninja DSA Questions
- Check if Array is Sorted
- Find the Missing Number in an Array
- Find the Second Largest Element in an Array
- Find Intersection of Two Arrays
- Detect Cycle in an Undirected Graph
- Remove Duplicates from Unsorted Linked List
- Count Inversions in an Array
- Reverse a Queue Using Recursion
- Convert Binary Tree to Doubly Linked List
- Check for Balanced Binary Tree
- Find Majority Element in an Array
- Sort Colors
- Remove Loop in Linked List
- Check if a Binary Tree is Symmetric
- Find Duplicates in O(n) Time and O(1) Space
- Find the Median of a Stream of Integers
- K Closest Points to Origin
- Word Search
- Serialize and Deserialize a Binary Tree
- Next Greater Element