# TCS DSA Questions with Answers

6 previously-asked dsa questions from TCS's hiring process, each with the correct answer and a worked explanation. Written against the company's actual test pattern.

_Source: Astra (https://useastra.in). Updated 2026-09-05._

### 1. Write an approach to reverse a singly linked list.

**Answer:** Iterate through the list with three pointers: prev (null), curr (head), and next. In each step save next = curr.next, point curr.next = prev, then move prev = curr and curr = next. When curr becomes null, prev is the new head. Time O(n), space O(1).

**Explanation:** Reverse a linked list in place using pointer reversal.

### 2. How would you check whether a given string is a palindrome?

**Answer:** Use two pointers, one at the start and one at the end. Compare characters while moving them toward the centre; if any pair differs it is not a palindrome. Ignore case or spaces if required. Time O(n), space O(1).

**Explanation:** Two-pointer comparison from both ends.

### 3. Print numbers from 1 to n, but for multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.

**Answer:** Loop from 1 to n. If i is divisible by 15 print FizzBuzz, else if divisible by 3 print Fizz, else if divisible by 5 print Buzz, else print i. Check the 15 case first.

**Explanation:** Classic FizzBuzz; check the combined divisor first.

### 4. Find the second largest element in an array in a single pass.

**Answer:** Track two variables, largest and second, both initialised to negative infinity. For each element, if it is greater than largest, set second = largest and largest = element; else if it is greater than second and not equal to largest, set second = element. Time O(n).

**Explanation:** Single pass tracking top two values.

### 5. Given an array and a target, determine whether any two numbers add up to the target.

**Answer:** Use a hash set. For each number x, check if target minus x is already in the set; if yes a pair exists. Otherwise add x to the set. Time O(n), space O(n).

**Explanation:** Hash set complement lookup.

### 6. Print a right angled star triangle of height n.

**Answer:** Use an outer loop i from 1 to n and an inner loop j from 1 to i printing a star, then a newline after the inner loop. Row i prints i stars. TCS frequently asks pattern questions like this.

**Explanation:** Nested loops; row i has i stars.

More TCS preparation, including the full recruitment process: https://useastra.in/campus/tcs
