# Coforge DSA Questions with Answers

6 previously-asked dsa questions from Coforge'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 second smallest element in an array.

**Answer:** Track smallest and secondSmallest, both set high initially. For each element, if it is smaller than smallest, move smallest to secondSmallest and update smallest; else if it is smaller than secondSmallest and not equal to smallest, update secondSmallest. Time O(n).

**Explanation:** Single pass tracking the two smallest values.

### 2. Check whether one string is a rotation of another.

**Answer:** If lengths differ, return false. Otherwise concatenate the first string with itself and check whether the second string is a substring of it. Time O(n) with an efficient substring search.

**Explanation:** Check substring of the doubled string.

### 3. Print all prime numbers up to n.

**Answer:** Use the Sieve of Eratosthenes: mark multiples of each prime starting from 2 as non-prime, then the unmarked numbers are prime. Time O(n log log n).

**Explanation:** Sieve of Eratosthenes.

### 4. Find the sum of all elements in an array.

**Answer:** Initialise a total to 0 and add each element in one pass. Return the total. Time O(n).

**Explanation:** Accumulate in a single pass.

### 5. Rotate an array to the right by k positions.

**Answer:** Take k modulo n. Reverse the whole array, then reverse the first k elements and the remaining n minus k elements. This rotates in place in O(n) time and O(1) space.

**Explanation:** Reversal algorithm for rotation.

### 6. Check whether a number is a power of two.

**Answer:** A positive number is a power of two if n AND (n-1) equals 0. Also ensure n is greater than 0. Time O(1).

**Explanation:** Bit trick n AND (n-1) equals 0.

More Coforge preparation, including the full recruitment process: https://useastra.in/campus/coforge
