# Cognizant DSA Questions with Answers

8 previously-asked dsa questions from Cognizant'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. Automata Fix: A function meant to sum all elements of an array a of size n uses the loop for(i=1; i<n; i++) sum += a[i]. It returns a wrong total. Identify and fix the bug.

**Answer:** The loop starts at i=1 and ends at i<n, so it skips a[0]. Fix it to for(i=0; i<n; i++) so every element is added.

### 2. Automata Fix: A factorial function returns 0 for every input. It initialises result = 0 and does result = result * i inside the loop. What is the bug?

**Answer:** Multiplying into a value initialised to 0 always yields 0. Initialise result = 1 before the multiplication loop.

### 3. Write a program to reverse an integer, for example 123 becomes 321.

**Answer:** Repeatedly take digit = n % 10, build rev = rev*10 + digit, then n = n/10 until n is 0. Handle sign and overflow. Time O(number of digits).

### 4. Find the largest element in an array.

**Answer:** Initialise max to the first element, iterate once and update max whenever a larger element is found. Time O(n).

### 5. Check whether a 3-digit number is an Armstrong number.

**Answer:** Sum the cubes of its digits and compare with the original number; if equal it is an Armstrong number (for example 153 = 1+125+27).

### 6. Count the frequency of each character in a string.

**Answer:** Use an array of size 256 (or a hash map); for each character increment its count, then print characters with their counts. Time O(n).

### 7. Automata Fix: A loop meant to print numbers from 1 to n prints nothing. It is written as for(i=1; i>n; i++) print(i). Fix it.

**Answer:** The condition i>n is false immediately for positive n. Change it to i<=n so the loop runs from 1 to n.

### 8. Swap two numbers without using a temporary variable.

**Answer:** Use a = a+b; b = a-b; a = a-b. Alternatively use XOR: a = a^b; b = a^b; a = a^b.

More Cognizant preparation, including the full recruitment process: https://useastra.in/campus/cognizant
