CAPGEMINI Coding Questions
Complete Java Solutions Guide
Author: Programming Practice Guide
Date: September 2025
Total Questions: 30
Table of Contents
String Manipulation (Questions 1-2, 7, 13, 16-17, 24, 27, 29-30)
Count vowels in a string
Reverse words in a sentence
Check if a string is a pangram
Replace spaces with hyphens
Count frequency of characters
Remove vowels from a string
Check if two strings are anagrams
Print ASCII values of characters
Remove special characters
Capitalize first letter of each word
Number Theory & Mathematics (Questions 3, 6, 8-12, 18-23, 28)
Check palindrome number
Sum of digits
Generate Fibonacci series
Check Armstrong number
Find GCD and LCM
Check prime number
Print prime numbers in range
Binary-decimal conversion
Find factorial
Print Pascal's Triangle
Count even/odd digits
Find missing number
Sum of even-position digits
Check perfect number
Array Operations (Questions 5, 14-15, 22, 26)
Find second largest element
Reverse array using 2-pointer
Find duplicate elements
Find missing number in array
Rotate array left/right
Pattern Printing (Questions 4, 20)
Print pyramid/star pattern
Print Pascal's Triangle
Matrix Operations (Question 25)
Matrix transpose and multiplication
String Manipulation Problems
Question 1: Count the Number of Vowels in a String
Problem Statement: Write a program to count the total number of vowels (a, e, i, o, u) in a given string.
Approach: Linear scan through the string checking each character.
Solution:
import java.util.*;
public class VowelCounter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toLowerCase();
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}
System.out.println("Number of vowels: " + count);
sc.close();
}
}
Algorithm:
1. Convert input string to lowercase for case-insensitive comparison
2. Iterate through each character in the string
3. Check if character is a vowel (a, e, i, o, u)
4. Increment counter if vowel is found
5. Return total count
Time Complexity: O(n) - Single pass through string
Space Complexity: O(1) - Constant extra space
Sample Input: "Hello World"
Sample Output: Number of vowels: 3
Question 2: Reverse Words in a Sentence
Problem Statement: Write a program to reverse the order of words in a given sentence while keeping the words
themselves intact.
Approach: Split sentence into words and reconstruct in reverse order.
Solution:
import java.util.*;
public class ReverseWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
StringBuilder result = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
result.append(words[i]);
if (i > 0) result.append(" ");
}
System.out.println("Reversed sentence: " + result.toString());
sc.close();
}
}
Algorithm:
1. Split the input sentence by spaces to get individual words
2. Create a StringBuilder to build the result
3. Iterate from last word to first word
4. Append each word to result with space separator
5. Return the reversed sentence
Time Complexity: O(n) - n is total characters
Space Complexity: O(n) - For storing split words
Sample Input: "Hello World Java"
Sample Output: Reversed sentence: Java World Hello
Number Theory & Mathematics Problems
Question 3: Check if a Number is a Palindrome
Problem Statement: Write a program to check if a given number reads the same forwards and backwards.
Approach: Reverse the number and compare with original.
Solution:
import java.util.*;
public class PalindromeNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int original = num;
int reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
if (original == reversed) {
System.out.println(original + " is a palindrome");
} else {
System.out.println(original + " is not a palindrome");
}
sc.close();
}
}
Algorithm:
1. Store the original number for comparison
2. Extract digits from right to left using modulo operation
3. Build reversed number by multiplying by 10 and adding current digit
4. Compare original and reversed numbers
5. Return true if they match, false otherwise
Time Complexity: O(log n) - Number of digits
Space Complexity: O(1) - Constant extra space
Sample Input: 12321
Sample Output: 12321 is a palindrome
Question 6: Sum of Digits of a Number
Problem Statement: Write a program to calculate the sum of all digits in a given number.
Approach: Extract each digit using modulo operation and add to sum.
Solution:
import java.util.*;
public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sum = 0;
int temp = Math.abs(num); // Handle negative numbers
while (temp > 0) {
sum += temp % 10;
temp /= 10;
}
System.out.println("Sum of digits: " + sum);
sc.close();
}
}
Algorithm:
1. Handle negative numbers by taking absolute value
2. Extract last digit using modulo 10
3. Add digit to running sum
4. Remove last digit by integer division by 10
5. Repeat until all digits are processed
Time Complexity: O(log n) - Number of digits
Space Complexity: O(1) - Constant extra space
Sample Input: 1234
Sample Output: Sum of digits: 10
Pattern Printing Problems
Question 4: Print a Pyramid/Star Pattern
Problem Statement: Write a program to print a pyramid pattern using stars (*) with given number of rows.
Approach: Print spaces for alignment followed by stars for each row.
Solution:
import java.util.*;
public class PyramidPattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
// Print spaces for center alignment
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// Print stars
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
sc.close();
}
}
Algorithm:
1. For each row i from 1 to n:
Print (n-i) spaces for center alignment
Print (2*i-1) stars to form pyramid shape
Move to next line
2. This creates a symmetric pyramid pattern
Time Complexity: O(n²) - Nested loops
Space Complexity: O(1) - Constant extra space
Sample Output for n=4:
*
***
*****
*******
Array Operations Problems
Question 5: Find the Second Largest Element in an Array
Problem Statement: Write a program to find the second largest element in an array of integers.
Approach: Sort array and find first element smaller than maximum.
Solution:
import java.util.*;
public class SecondLargest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter array size: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
// Find second largest (distinct element)
int secondLargest = arr[n-1];
for (int i = n-2; i >= 0; i--) {
if (arr[i] < arr[n-1]) {
secondLargest = arr[i];
break;
}
}
System.out.println("Second largest element: " + secondLargest);
sc.close();
}
}
Algorithm:
1. Read array elements from user input
2. Sort the array in ascending order
3. Start from second last element
4. Find first element that is smaller than the largest
5. This gives us the second largest distinct element
Time Complexity: O(n log n) - Due to sorting
Space Complexity: O(1) - Constant extra space
Sample Input: [5, 2, 8, 1, 9, 3]
Sample Output: Second largest element: 8
Question 14: Reverse an Array Using 2-Pointer Technique
Problem Statement: Write a program to reverse an array using the two-pointer approach.
Approach: Use two pointers from start and end, swap elements and move towards center.
Solution:
import java.util.*;
public class ReverseArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter array size: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Two pointer approach
int left = 0, right = n - 1;
while (left < right) {
// Swap elements at left and right positions
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
System.out.println("Reversed array:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
sc.close();
}
}
Algorithm:
1. Initialize two pointers: left at start (0) and right at end (n-1)
2. While left pointer is less than right pointer:
Swap elements at left and right positions
Move left pointer one step right
Move right pointer one step left
3. Continue until pointers meet or cross
Time Complexity: O(n) - Single pass through array
Space Complexity: O(1) - In-place reversal
Sample Input: [1, 2, 3, 4, 5]
Sample Output: Reversed array: 5 4 3 2 1
Advanced Problems
Question 8: Generate Fibonacci Series up to N Terms
Problem Statement: Write a program to generate and display the Fibonacci series up to N terms.
Approach: Use iterative method with two variables to track previous terms.
Solution:
import java.util.*;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = sc.nextInt();
if (n <= 0) {
System.out.println("Please enter a positive number");
return;
}
System.out.print("Fibonacci Series: ");
if (n >= 1) System.out.print("0 ");
if (n >= 2) System.out.print("1 ");
int a = 0, b = 1;
for (int i = 3; i <= n; i++) {
int next = a + b;
System.out.print(next + " ");
a = b;
b = next;
}
System.out.println();
sc.close();
}
}
Algorithm:
1. Handle base cases: first term is 0, second term is 1
2. For subsequent terms, calculate as sum of previous two terms
3. Use two variables to track the last two terms
4. Update variables for next iteration
5. Continue until N terms are generated
Time Complexity: O(n) - Generate n terms
Space Complexity: O(1) - Constant extra space
Sample Input: 7
Sample Output: Fibonacci Series: 0 1 1 2 3 5 8
Question 11: Check for Prime Number
Problem Statement: Write a program to check if a given number is prime or not.
Approach: Optimized trial division checking divisibility up to square root.
Solution:
import java.util.*;
public class PrimeNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (isPrime(num)) {
System.out.println(num + " is a prime number");
} else {
System.out.println(num + " is not a prime number");
}
sc.close();
}
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
// Check for divisors of form 6k±1 up to √n
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
}
Algorithm:
1. Handle edge cases: numbers ≤ 1 are not prime
2. Handle small primes: 2 and 3 are prime
3. Check divisibility by 2 and 3
4. Check divisors of form 6k±1 up to √n
5. This optimization reduces time complexity significantly
Time Complexity: O(√n) - Check divisors up to square root
Space Complexity: O(1) - Constant extra space
Mathematical Insight: All primes > 3 are of form 6k±1
Sample Input: 17
Sample Output: 17 is a prime number
Question 25: Matrix Operations (Transpose & Multiplication)
Problem Statement: Write a program to perform matrix transpose and matrix multiplication operations.
Approach: Implement both operations with proper dimension checking.
Solution:
import java.util.*;
public class MatrixOperations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Matrix Operations Menu:");
System.out.println("1. Matrix Transpose");
System.out.println("2. Matrix Multiplication");
System.out.print("Choose operation (1-2): ");
int choice = sc.nextInt();
switch(choice) {
case 1:
performTranspose(sc);
break;
case 2:
performMultiplication(sc);
break;
default:
System.out.println("Invalid choice!");
}
sc.close();
}
static void performTranspose(Scanner sc) {
System.out.print("Enter matrix dimensions (rows cols): ");
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
System.out.println("Enter matrix elements row by row:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = sc.nextInt();
}
}
System.out.println("\nOriginal Matrix:");
printMatrix(matrix, rows, cols);
System.out.println("\nTranspose Matrix:");
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
static void performMultiplication(Scanner sc) {
System.out.print("Enter first matrix dimensions (rows cols): ");
int r1 = sc.nextInt(), c1 = sc.nextInt();
System.out.print("Enter second matrix dimensions (rows cols): ");
int r2 = sc.nextInt(), c2 = sc.nextInt();
if (c1 != r2) {
System.out.println("Error: Matrix multiplication not possible!");
System.out.println("Columns of first matrix must equal rows of second matrix.")
return;
}
int[][] mat1 = readMatrix(sc, r1, c1, "first");
int[][] mat2 = readMatrix(sc, r2, c2, "second");
int[][] result = multiplyMatrices(mat1, mat2, r1, c1, c2);
System.out.println("\nFirst Matrix:");
printMatrix(mat1, r1, c1);
System.out.println("\nSecond Matrix:");
printMatrix(mat2, r2, c2);
System.out.println("\nResult Matrix:");
printMatrix(result, r1, c2);
}
static int[][] readMatrix(Scanner sc, int rows, int cols, String matrixName) {
int[][] matrix = new int[rows][cols];
System.out.println("Enter " + matrixName + " matrix elements:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = sc.nextInt();
}
}
return matrix;
}
static int[][] multiplyMatrices(int[][] mat1, int[][] mat2, int r1, int c1, int c2) {
int[][] result = new int[r1][c2];
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
return result;
}
static void printMatrix(int[][] matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.printf("%4d ", matrix[i][j]);
}
System.out.println();
}
}
}
Algorithms:
Transpose:
1. For matrix A[m][n], transpose A^T[n][m]
2. A^T[j][i] = A[i][j] for all valid i, j
3. Simply swap row and column indices during printing
Multiplication:
1. For A[m×n] × B[n×p] = C[m×p]
2. C[i][j] = Σ(A[i][k] × B[k][j]) for k = 0 to n-1
3. Verify that columns of A equal rows of B
Time Complexity:
Transpose: O(m×n)
Multiplication: O(m×n×p)
Space Complexity: O(m×p) for result matrix
Quick Reference Guide
Problem Categories Summary
Category Questions Key Concepts
String
1, 2, 7, 13, 16, 17, 24, 27, 29, 30 Character manipulation, StringBuilder, String methods
Processing
3, 6, 8, 9, 10, 11, 12, 18, 19, 21, 23, Mathematical algorithms, digit extraction, prime
Number Theory
28 numbers
Arrays 5, 14, 15, 22, 26 Sorting, two-pointer technique, searching
Patterns 4, 20 Nested loops, mathematical patterns
Matrix 25 2D arrays, matrix operations
Time Complexity Quick Reference
Complexity Problems Description
O(1) - Constant time operations
O(log n) 3, 6, 9, 18, 19, 21, 22, 23, 28 Logarithmic operations, digit processing
O(n) 1, 2, 7, 8, 13, 14, 15, 16, 17, 26, 27, 29, 30 Linear scan algorithms
O(n log n) 5, 24 Sorting-based solutions
Complexity Problems Description
O(n²) 4, 20 Nested loop patterns
O(n × √n) 12 Prime checking in range
Common Programming Patterns
1. Two-Pointer Technique
int left = 0, right = n - 1;
while (left < right) {
// Process elements at left and right
// Move pointers towards center
left++; right--;
}
2. Digit Extraction
while (num > 0) {
int digit = num % 10; // Extract last digit
// Process digit
num /= 10; // Remove last digit
}
3. Frequency Counting
HashMap<Character, Integer> freq = new HashMap<>();
for (char ch : str.toCharArray()) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
4. Array Reversal (In-place)
for (int i = 0; i < n/2; i++) {
int temp = arr[i];
arr[i] = arr[n-1-i];
arr[n-1-i] = temp;
}
Tips for Coding Interviews
1. Always clarify requirements before coding
2. Think about edge cases (empty input, negative numbers, etc.)
3. Start with brute force, then optimize
4. Write clean, readable code with proper variable names
5. Test with sample inputs mentally
6. Explain your approach while coding
7. Consider time and space complexity
Common Mistakes to Avoid
Off-by-one errors in loops and array indices
Integer overflow for large numbers (use long when needed)
Null pointer exceptions - always check for null inputs
Array index out of bounds - validate array access
Infinite loops - ensure loop conditions will eventually become false
Conclusion
This comprehensive guide covers all 30 essential Capgemini coding questions with detailed solutions, explanations, and
analysis. Each solution is optimized for both readability and efficiency, making it perfect for interview preparation and
coding practice.
Remember: Consistent practice and understanding of underlying concepts is key to success in coding interviews!