The TCS National Qualifier Test (TCS NQT) is an essential gateway for candidates aspiring to work at Tata Consultancy Services (TCS), one of the largest IT companies globally. The exam assesses a range of skills, including logical reasoning, quantitative ability, and coding. Among these, the Advanced Coding section is often considered the most challenging part of the exam. This section is designed to test your proficiency in programming, problem-solving, and the application of algorithms and data structures.

Mastering coding for the TCS NQT is crucial because it not only affects your overall score but also showcases your ability to handle real-world coding problems, which is a key skill in the IT industry. In this comprehensive guide, weâ€™ll provide detailed insights into the TCS NQT Advanced Coding section, including problem-solving strategies, common coding topics, and example questions with their corresponding solutions. By the end of this article, you will be better prepared to tackle the TCS NQT Advanced Coding section and improve your chances of success.

## Understanding TCS NQT Advanced Coding Questions

The Advanced Coding section in the TCS NQT is designed to test your problem-solving abilities in programming. Typically, youâ€™ll be asked to solve 1â€“2 coding problems, which may range from easy to hard, depending on the difficulty level. Understanding the structure of these questions and practising similar problems is essential for success.

### TCS NQT Advanced Coding Question Types and Formats

In the Advanced Coding section, the problems are generally presented as programming challenges. Youâ€™ll be required to write efficient code to solve the given problem, often with multiple test cases. The format usually involves:

- A detailed problem statement
- Input format specifications
- Output format specifications
- Constraints (e.g., time and space limits)
- Test cases (both visible and hidden)

Youâ€™ll need to ensure that your solution passes all test cases within the provided time limits.

### TCS NQT Advanced Coding Difficulty Levels

Coding questions in the TCS NQT can be broadly categorised into three difficulty levels:

**Easy:**These questions require basic problem-solving and the use of simple data structures like arrays or strings.**Medium:**These questions are more complex and may require knowledge of algorithms like sorting, searching, and recursion.**Hard:**These are the most challenging questions, often involving dynamic programming, advanced data structures like trees and graphs, or complex algorithmic concepts.

### Common TCS NQT Advanced Coding Concepts Tested

The most common coding concepts tested in the TCS NQT Advanced Coding section include:

**Data Structures:**Arrays, linked lists, stacks, queues, trees, and graphs.**Algorithms:**Sorting, searching, dynamic programming, greedy algorithms, backtracking, and divide-and-conquer techniques.**Problem-solving:**Your ability to break down a complex problem into smaller subproblems, design algorithms, and implement them efficiently.

Now that you know what to expect, let’s look at some examples of TCS NQT Advanced Coding Questions.

## TCS NQT Advanced Coding Questions & Answers

Here are a few examples of TCS NQT Advanced Coding Questions. We will also provide the answers and explanations.

### TCS NQT Advanced Coding Questions: Data Structures

#### 1) Arrays

**Question:**

Write a program to find the second largest element in an array of integers.

**Input:**

An integer array arr[] of size n where n >= 2.

**Output:**

The second largest element in the array.

**Example:**

makefile

Input: arr[] = [12, 35, 1, 10, 34, 1]

Output: 34

**Solution:**

To solve this problem, you can first find the largest element and then find the second largest by iterating through the array. Hereâ€™s the code:

python

def second_largest(arr):

first = second = -float(‘inf’)

for num in arr:

if num > first:

second = first

first = num

elif num > second and num != first:

second = num

return second

arr = [12, 35, 1, 10, 34, 1]

print(“Second largest element is:”, second_largest(arr))

#### 2) Linked Lists

**Question:**

Write a function to reverse a linked list.

**Input:**

A singly linked list.

**Output:**

The reversed linked list.

**Example:**

rust

Input: 1 -> 2 -> 3 -> 4 -> NULL

Output: 4 -> 3 -> 2 -> 1 -> NULL

**Solution:**

We can reverse a linked list by changing the next pointers of each node. Hereâ€™s how you can do it:

python

class Node:

def __init__(self, data):

self.data = data

self.next = None

def reverse_linked_list(head):

prev = None

current = head

while current is not None:

next_node = current.next

current.next = prev

prev = current

current = next_node

return prev

# Helper function to print the linked list

def print_linked_list(head):

while head:

print(head.data, end=” -> “)

head = head.next

print(“NULL”)

# Creating a linked list 1 -> 2 -> 3 -> 4

head = Node(1)

head.next = Node(2)

head.next.next = Node(3)

head.next.next.next = Node(4)

# Reversing the linked list

reversed_head = reverse_linked_list(head)

print_linked_list(reversed_head)

#### 3) Stacks

**Question:**

Write a program to check if a given string of parentheses is balanced.

**Input:**

A string containing parentheses ( and ).

**Output:**

Return True if the string is balanced, else False.

**Example:**

vbnet

Input: “(())”

Output: True

Input: “(()”

Output: False

**Solution:**

This problem can be solved using a stack to keep track of open parentheses. For every closing parenthesis, check if thereâ€™s a corresponding open parenthesis in the stack.

python

def is_balanced(s):

stack = []

for char in s:

if char == ‘(‘:

stack.append(char)

elif char == ‘)’:

if not stack:

return False

stack.pop()

return len(stack) == 0

s = “(())”

print(“Is balanced:”, is_balanced(s))

#### 4) Queues

**Question:**

Write a function to implement a queue using two stacks.

**Input:**

Operations like enqueue and dequeue.

**Output:**

The corresponding queue behaviour using two stacks.

**Solution:**

We can simulate a queue using two stacks. One stack is used for enqueue operations, and the other for dequeue operations.

python

class Queue:

def __init__(self):

self.stack1 = []

self.stack2 = []

def enqueue(self, x):

self.stack1.append(x)

def dequeue(self):

if not self.stack2:

while self.stack1:

self.stack2.append(self.stack1.pop())

return self.stack2.pop() if self.stack2 else None

q = Queue()

q.enqueue(1)

q.enqueue(2)

q.enqueue(3)

print(q.dequeue()) # Output: 1

print(q.dequeue()) # Output: 2

#### 5) Trees

**Question:**

Write a function to perform inorder traversal of a binary tree.

**Input:**

A binary tree.

**Output:**

The inorder traversal of the tree.

**Example:**

yaml

Input: [1, null, 2, 3]

Output: [1, 3, 2]

**Solution:**

Inorder traversal is a depth-first traversal that visits the left subtree, the root, and then the right subtree.

python

class TreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

def inorder_traversal(root):

result = []

def traverse(node):

if node is not None:

traverse(node.left)

result.append(node.value)

traverse(node.right)

traverse(root)

return result

# Constructing a simple binary tree

root = TreeNode(1)

root.right = TreeNode(2)

root.right.left = TreeNode(3)

print(“Inorder Traversal:”, inorder_traversal(root))

#### 6) Graphs

**Question:**

Write a function to perform a breadth-first search (BFS) on a graph.

**Input:**

An adjacency list representation of a graph and a starting node.

**Output:**

A list of nodes visited in BFS order.

**Solution:**

BFS explores all the nodes at the current level before moving to the next level. It is implemented using a queue.

python

from collections import deque

def bfs(graph, start):

visited = []

queue = deque([start])

while queue:

node = queue.popleft()

if node not in visited:

visited.append(node)

queue.extend([neighbor for neighbor in graph[node] if neighbor not in visited])

return visited

# Representing graph using adjacency list

graph = {

‘A’: [‘B’, ‘C’],

‘B’: [‘D’, ‘E’],

‘C’: [‘F’],

‘D’: [],

‘E’: [‘F’],

‘F’: []

}

print(“BFS traversal starting from ‘A’:”, bfs(graph, ‘A’))

### TCS NQT Advanced Coding Questions: Algorithms

#### 1) Sorting Algorithms

Sorting algorithms are used to arrange elements in a specific order, usually ascending or descending. Here are some commonly used sorting algorithms:

- Bubble Sort: Repeatedly swapping adjacent elements if they are in the wrong order.
- Insertion Sort: Building the sorted array one element at a time by comparing and inserting each element in its proper place.
- Selection Sort: Finding the minimum element from the unsorted part of the array and swapping it with the first element.
- Merge Sort: Dividing the array into two halves, sorting each half, and then merging them.
- Quick Sort: Selecting a pivot element, partitioning the array around the pivot, and then sorting the partitions.

**Question:**

Write a Python program to implement quicksort.

**Input:**

An unsorted array.

**Output:**

The sorted array.

**Solution:**

Quicksort is a divide-and-conquer algorithm that selects a pivot and partitions the array around the pivot.

python

def quicksort(arr):

if len(arr) <= 1:

return arr

pivot = arr[len(arr) // 2]

left = [x for x in arr if x < pivot]

middle = [x for x in arr if x == pivot]

right = [x for x in arr if x > pivot]

return quicksort(left) + middle + quicksort(right)

arr = [3, 6, 8, 10, 1, 2, 1]

print(“Sorted array:”, quicksort(arr))

#### 2) Searching Algorithms

Searching algorithms are used to find an element in a dataset. Two common searching algorithms include:

- Linear Search: Checking each element in the list sequentially until the target element is found.
- Binary Search: Dividing the array into halves and checking the middle element, reducing the search space in each step.

**Question:**

Write a Python program to implement binary search.

**Input:**

A sorted array and a target value.

**Output:**

The index of the target value, or -1 if the target is not found.

python

def binary_search(arr, target):

low, high = 0, len(arr) – 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

low = mid + 1

else:

high = mid – 1

return -1

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

target = 5

print(“Target found at index:”, binary_search(arr, target))

#### 3) Dynamic Programming

Dynamic programming is a technique for solving complex problems by breaking them down into simpler subproblems and storing the solutions to avoid redundant calculations.

**Question:**

Write a program to find the nth Fibonacci number using dynamic programming.

**Input:**

An integer n.

**Output:**

The nth Fibonacci number.

python

def fibonacci(n):

dp = [0] * (n + 1)

dp[1] = 1

for i in range(2, n + 1):

dp[i] = dp[i – 1] + dp[i – 2]

return dp[n]

n = 10

print(f”The {n}th Fibonacci number is:”, fibonacci(n))

#### 4) Greedy Algorithms

Greedy algorithms work by making the best choice at each step, hoping to find the global optimum.

**Question:**

Write a Python program to find the minimum number of coins needed to make a given value.

**Input:**

A value V and an array coins[] representing different coin denominations.

**Output:**

The minimum number of coins needed to make the value V.

**Solution:**

python

def min_coins(coins, V):

result = []

coins.sort(reverse=True)

for coin in coins:

while V >= coin:

V -= coin

result.append(coin)

return len(result)

coins = [1, 2, 5, 10, 20, 50, 100]

V = 93

print(f”Minimum coins required: {min_coins(coins, V)}”)

#### 5) Backtracking

Backtracking is a technique used to solve problems by trying different solutions and discarding those that fail to satisfy the conditions.

**Question:**

Write a Python program to solve the N-Queens problem using backtracking.

**Input:**

An integer n representing the size of the chessboard.

**Output:**

All possible configurations to place n queens on the chessboard so that no two queens threaten each other.

python

def is_safe(board, row, col):

for i in range(col):

if board[row][i] == 1:

return False

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):

if board[i][j] == 1:

return False

for i, j in zip(range(row, len(board)), range(col, -1, -1)):

if board[i][j] == 1:

return False

return True

def solve_nqueens_util(board, col):

if col >= len(board):

return True

for i in range(len(board)):

if is_safe(board, i, col):

board[i][col] = 1

if solve_nqueens_util(board, col + 1):

return True

board[i][col] = 0

return False

def solve_nqueens(n):

board = [[0 for _ in range(n)] for _ in range(n)]

if solve_nqueens_util(board, 0):

for row in board:

print(row)

else:

print(“No solution exists”)

n = 4

solve_nqueens(n)

#### 6) Divide and Conquer

Divide and conquer algorithms break down a problem into smaller subproblems, solve each subproblem, and combine the results to solve the original problem.

**Question:**

Write a Python program to implement merge sort.

**Input:**

An unsorted array.

**Output:**

The sorted array.

python

def merge_sort(arr):

if len(arr) > 1:

mid = len(arr) // 2

left_half = arr[:mid]

right_half = arr[mid:]

merge_sort(left_half)

merge_sort(right_half)

i = j = k = 0

while i < len(left_half) and j < len(right_half):

if left_half[i] < right_half[j]:

arr[k] = left_half[i]

i += 1

else:

arr[k] = right_half[j]

j += 1

k += 1

while i < len(left_half):

arr[k] = left_half[i]

i += 1

k += 1

while j < len(right_half):

arr[k] = right_half[j]

j += 1

k += 1

arr = [38, 27, 43, 3, 9, 82, 10]

merge_sort(arr)

print(“Sorted array:”, arr)

These questions were just a sample. To improve your problem-solving skills, let’s explore some common approaches to solving TCS NQT Advanced Coding Questions.

## TCS NQT Advanced Coding Problem-solving Approaches

There are several approaches you can use to solve TCS NQT Advanced Coding Questions. These include brute force, divide and conquer, dynamic programming, and greedy algorithms.

### 1) Understanding the Problem Statement

The first and most important step in solving any coding problem is understanding the problem statement. Read it carefully to grasp what is being asked, including the input format, output format, and constraints.

### 2) Breaking Down the Problem into Smaller Subproblems

Once you understand the problem, try to break it down into smaller, more manageable subproblems. For example, if you are asked to find the largest element in a list, you can first try to find the largest element in smaller segments.

### 3) Developing a Solution Algorithm

After breaking down the problem, develop an algorithm to solve each subproblem. Focus on creating an efficient solution that fits within the given time and space constraints.

### 4) Implementing the Algorithm in Code

Once you have a clear algorithm, the next step is to implement it in code. Make sure your code is clean and readable, with comments where necessary.

### 5) Testing and Debugging the Code

Testing your code is a crucial part of problem-solving. Run your code with various test cases, including edge cases, to ensure it behaves as expected. If you encounter errors, debug the code by tracking variable values and conditions.

Understanding these approaches will help you tackle TCS NQT Advanced Coding Questions effectively. Now, let’s discuss some tips to help you succeed.

## Tips for Solving TCS NQT Advanced Coding Questions

Here are some tips to help you solve TCS NQT Advanced Coding Questions. These tips will improve your problem-solving skills and increase your chances of success.

### 1) Time Management Strategies

Efficient time management is key to completing the coding section successfully. Prioritise easier problems, and if youâ€™re stuck on a complex one, move to the next and return later.

### 2) Code Optimization Techniques

After solving the problem, focus on optimising your code for time and space complexity. Use efficient data structures, avoid unnecessary computations, and minimise recursive calls.

### 3) Debugging Best Practices

When debugging, break the problem down into smaller parts and test each part individually. Use print statements or a debugger to trace variable values and find the source of the error.

## Conclusion

Mastering the TCS NQT Advanced Coding section requires consistent practice, an understanding of data structures and algorithms, and the ability to approach problems systematically. The questions may vary in difficulty, but with the right strategies and a clear problem-solving mindset, you can excel. The examples provided in this article should give you a good starting point to prepare effectively.

Remember, coding is a skill that improves with practice. By solving different types of coding problems and working on your time management and optimization techniques, youâ€™ll increase your chances of success in the TCS NQT exam. Keep practising, stay confident, and approach each coding challenge with a clear mind. Good luck!

## TCS NQT Advanced Coding FAQs

### 1) Are TCS NQT coding questions hard?

Yes, TCS NQT coding questions can be challenging. They often require a deep understanding of data structures, algorithms, and problem-solving skills. The questions are designed to test your ability to think critically and come up with efficient solutions within a limited time frame.

### 2) Is TCS NQT hard to crack?

The difficulty of TCS NQT depends on your preparation and understanding of the topics covered. While the exam is challenging, it is definitely possible to crack if you put in the right effort. Focus on practicing coding problems, understanding data structures and algorithms, and improving your problem-solving skills.

### 3) Can we qualify TCS NQT without coding?

No, you cannot qualify TCS NQT without coding. The coding section is a major component of the exam, and it is essential to demonstrate your coding skills to be successful. Even if you perform well in other sections, a weak performance in the coding section will likely result in disqualification.

### 4) Is IT easy to pass TCS NQT?

Passing TCS NQT is not easy, even for IT students. While IT students may have a slight advantage due to their exposure to coding, they still need to practice and prepare thoroughly to compete with other candidates. The key to success lies in understanding the concepts, practicing regularly, and developing effective problem-solving strategies.