# Tech Mahindra DSA Questions with Answers

6 previously-asked dsa questions from Tech Mahindra'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. Find the middle element of a singly linked list in one pass.

**Answer:** Use two pointers: a slow pointer moving one node and a fast pointer moving two nodes per step. When the fast pointer reaches the end, the slow pointer is at the middle. Time O(n), space O(1).

**Explanation:** Slow and fast pointer technique.

### 2. Check whether a string contains only digits.

**Answer:** Iterate over each character and verify it lies between 0 and 9 (or use an is-digit check). Return false on the first non-digit, true if all pass. Time O(n).

**Explanation:** Validate each character is a digit.

### 3. Print Floyd triangle up to n rows.

**Answer:** Maintain a running counter starting at 1. For each row i from 1 to n, print i consecutive numbers from the counter, incrementing it each time, then a newline. Time O(n^2).

**Explanation:** Nested loops with a running counter.

### 4. Find the LCM of two numbers.

**Answer:** Compute the GCD using the Euclidean algorithm, then LCM = (a * b) / gcd. Divide before multiplying to reduce overflow risk. Time O(log(min(a, b))).

**Explanation:** LCM from GCD: a*b/gcd.

### 5. Count the number of consonants in a string.

**Answer:** Iterate the string, and for each alphabetic character that is not a vowel, increment a counter. Convert to a single case first for simplicity. Time O(n).

**Explanation:** Count alphabetic non-vowel characters.

### 6. Find the third largest element in an array.

**Answer:** Track the three largest distinct values (first, second, third) in a single pass, shifting them when a larger value appears. Return third. Handle arrays with fewer than three distinct values. Time O(n).

**Explanation:** Track the top three distinct values.

More Tech Mahindra preparation, including the full recruitment process: https://useastra.in/campus/tech-mahindra
