Fill your College Details

Summarise With AI
Back

Top Infosys Coding Questions with Solutions: Ace Your Interview

22 Jun 2026
3 min read

Key Takeaways From The Blog

  • Explore frequently asked Infosys coding questions covering algorithms, data structures, and mathematical problem-solving concepts.
  • Understand the difficulty levels of Infosys coding questions, from easy (sorting and searching) to medium (dynamic programming and greedy algorithms) and hard (graphs and advanced DSA).
  • Access coding solutions in popular programming languages, including C, C++, Java, and Python.
  • Learn practical coding strategies, optimization techniques, and preparation tips to improve your performance in the Infosys online coding test.
  • Build confidence for assessments and interviews through real-world examples, structured practice, and expert preparation guidance.

Introduction

Preparing for Infosys interviews can feel overwhelming, but understanding the types of Infosys coding questions asked is a great start. Infosys, a leading IT company, tests candidates on problem-solving and coding skills to find those who can handle real-world tech tasks. This blog covers common coding questions, their difficulty levels, and solutions in simple languages. By the end, you'll have tips to practice and succeed.

Traditional coding prep often focuses on theory, but Infosys wants practical skills. Many students struggle with applying concepts under time pressure. This blog solves that by offering questions, answers, and strategies to build confidence.

The Changing Landscape of Coding Interviews

Coding interviews have changed from simple puzzles to real-world problems. Infosys now tests how candidates solve tasks like optimizing data or building secure systems. This shift means students need practice with actual questions to succeed.

Why Coding Matters: Coding tests show your ability to think logically and write clean code, key for tech jobs

Types of Coding Questions Asked in Infosys

1. Algorithm-based Questions

  • Sorting Algorithms (e.g., Quick Sort, Merge Sort)
  • Searching Algorithms (e.g., Binary Search, Linear Search)
  • Dynamic Programming (e.g., Fibonacci, Knapsack Problem)
  • Greedy Algorithms (e.g., Activity Selection)
  • Backtracking (e.g., N-Queens Problem)

2. Data Structure Questions

  • Arrays (e.g., Rotation, Merging)
  • Linked Lists (e.g., Reversal, Cycle Detection)
  • Stacks (e.g., Parenthesis Matching)
  • Queues (e.g., Implementing with Stacks)
  • Trees (e.g., Traversal, Height Calculation)
  • Graphs (e.g., BFS, DFS)

3. String Manipulation

  • String Reversal
  • Anagram Checking
  • Substring Search (e.g., Rabin-Karp Algorithm)
  • Palindrome Checking
  • Character Counting

4. Mathematical Problems

  • Prime Number Generation (e.g., Sieve of Eratosthenes)
  • Factorial Calculation
  • Fibonacci Sequence
  • GCD and LCM Calculations
  • Combinatorial Problems (e.g., Pascal's Triangle)

Understanding the Difficulty Levels of Infosys Coding Questions

While preparing for coding interviews or competitive programming, one of the biggest challenges candidates face is the varying difficulty levels of Infosys coding questions. These questions are generally categorized into three levels, easy, medium, and hard, based on their complexity and the depth of algorithmic knowledge required to solve them. Understanding these difficulty levels helps candidates identify the skills they need to develop and create a structured preparation strategy. In the following sections, we'll explore each category and explain the concepts and problem-solving approaches commonly associated with them.

Easy Level Questions

Easy-level coding questions asked in Infosys online test are generally aimed at checking your elementary programming knowledge, along with your grasp of the basic concepts. Such problems can be about using simple data structures like arrays, strings, and linked lists. The main point is to measure your skill in writing efficient and readable code for the given algorithms.

At this stage, candidates are expected to demonstrate proficiency in:

  • Basic loops and conditionals
  • Array manipulations
  • String operations

These questions are often solved through direct implementation without the need for advanced algorithmic knowledge. You might encounter problems like finding the maximum or minimum in an array or reversing a string.

Medium Level Questions

Medium-level Infosys coding questions are generally more challenging and require candidates to apply advanced problem-solving techniques. These questions often involve concepts such as dynamic programming, greedy algorithms, recursion, and efficient data structures. Beyond testing theoretical knowledge, they assess a candidate's ability to break down complex problems, identify optimal approaches, and write time-efficient solutions. Developing these skills is crucial for performing well in the Infosys online coding test and technical interviews.

  • Dynamic Programming (DP): Solves problems by breaking them into smaller subproblems and reusing intermediate results. Examples include 0/1 Knapsack and Longest Common Subsequence.
  • Greedy Algorithms: Finds optimal solutions by making the best choice at each step. Common examples include activity selection and coin change problems.

At this level, candidates may encounter pure greedy problems, hybrid approaches combining greedy techniques with other methods, and optimization problems that require efficient decision-making. Mastering these concepts is essential for solving medium-difficulty coding questions in the Infosys online coding test.

Hard Level Questions

Usually, hard level questions demand the candidates to thoroughly understand advanced algorithmic techniques. Such problems generally entail the combination of several concepts, and thus the resolution of these problems needs to be inventive and the candidates to have excellent problem-solving skills. 

The solutions to these coding questions asked in Infosys online test might require advanced dynamic programming techniques, optimization methods, or in-depth knowledge of complex data structures. Examples include:

  • Graph algorithms (e.g., Dijkstra’s, Bellman-Ford)
  • String matching algorithms
  • Advanced greedy strategies
  • Computational geometry

In these hard-level problems, candidates might need to:

  • Utilize dynamic programming with complex state transitions.
  • Apply greedy algorithms in combination with other techniques, such as backtracking or divide and conquer.

What We’ve Learned So Far: Infosys questions test algorithms, data structures, strings, and math—practice these to build a strong foundation.

Top Coding Questions With Answers Asked in Infosys

Based on common questions from sources, here are the formatted versions of the provided coding questions. Each includes a problem statement, input format, output format, sample input and output, solutions in C, C++, Java, and Python (with codes modified for consistency to take user input where applicable), and a code explanation.

1. Swap Two Numbers Using a Temporary Variable

Problem Statement

Write a program to swap two numbers using a temporary variable.

Input Format

  • First line: an integer a
  • Second line: an integer b

Output Format

  • Print "Before swapping: a = , b = "
  • Print "After swapping: a = , b = "

Sample Input

5

10

Sample Output

Before swapping: a = 5, b = 10

After swapping: a = 10, b = 5

Solutions

C

#include <stdio.h>

int main() {
    int a, b, temp;
    scanf("%d", &a);
    scanf("%d", &b);

    printf("Before swapping: a = %d, b = %d\n", a, b);

    // Swap using a temporary variable
    temp = a;
    a = b;
    b = temp;

    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}

C++

#include <iostream>
using namespace std;

int main() {
    int a, b, temp;
    cin >> a >> b;

    cout << "Before swapping: a = " << a << ", b = " << b << endl;

    // Swap using a temporary variable
    temp = a;
    a = b;
    b = temp;

    cout << "After swapping: a = " << a << ", b = " << b << endl;
    return 0;
}

Java

import java.util.Scanner;

public class SwapNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        int a = scanner.nextInt();
        int b = scanner.nextInt();

        System.out.println("Before swapping: a = " + a + ", b = " + b);

        // Swap using a temporary variable
        int temp = a;
        a = b;
        b = temp;

        System.out.println("After swapping: a = " + a + ", b = " + b);
        scanner.close();
    }
}

Python

a = int(input())
b = int(input())

print("Before swapping: a =", a)
print("Before swapping: b =", b)

# Swap using a temporary variable
temp = a
a = b
b = temp

print("After swapping: a =", a)
print("After swapping: b =", b)

Explanation of Code

The program takes two integers as input. It outputs the integers as they are, performs the swap operation using a temporary variable, and then outputs the integers after swapping. This method is simple and has a constant time complexity. 

2. Convert Decimal Number to Binary Number

Problem Statement

Write a program to convert a decimal number to its binary representation.

Input Format

  • First line: an integer n (decimal number)

Output Format

  • Print "Binary representation of <n> is: <binary>"

Sample Input

11

Sample Output

Binary representation of 11 is: 1011

Solutions

C

#include <stdio.h>

void convertToBinary(int num) {
    if (num == 0) {
        printf("0");
        return;
    }
    int binary[32], i = 0;

    while (num > 0) {
        binary[i] = num % 2;
        num /= 2;
        i++;
    }

    // Print binary in reverse order
    for (int j = i - 1; j >= 0; j--) {
        printf("%d", binary[j]);
    }
}

int main() {
    int n;
    scanf("%d", &n);
    printf("Binary representation of %d is: ", n);
    convertToBinary(n);
    printf("\n");
    return 0;
}

C++

#include <iostream>
using namespace std;

void convertToBinary(int num) {
    if (num == 0) {
        cout << "0";
        return;
    }
    int binary[32];
    int i = 0;

    while (num > 0) {
        binary[i] = num % 2;
        num /= 2;
        i++;
    }

    // Print binary in reverse order
    for (int j = i - 1; j >= 0; j--) {
        cout << binary[j];
    }
}

int main() {
    int n;
    cin >> n;
    cout << "Binary representation of " << n << " is: ";
    convertToBinary(n);
    cout << endl;
    return 0;
}

Java

import java.util.Scanner;

public class DecimalToBinary {
    public static void convertToBinary(int num) {
        if (num == 0) {
            System.out.print("0");
            return;
        }
        StringBuilder binary = new StringBuilder();

        while (num > 0) {
            binary.append(num % 2);
            num /= 2;
        }

        System.out.print(binary.reverse().toString());
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.print("Binary representation of " + n + " is: ");
        convertToBinary(n);
        System.out.println();
        scanner.close();
    }
}

Python

def convert_to_binary(num):
    if num == 0:
        return "0"
    binary = []
    while num > 0:
        binary.append(str(num % 2))
        num //= 2
    binary.reverse()
    return ''.join(binary)

n = int(input())
binary_representation = convert_to_binary(n)
print(f"Binary representation of {n} is: {binary_representation}")

Explanation of Code

The program takes two integers as input. It outputs the integers as they are, performs the swap operation using a temporary variable, and then outputs the integers after swapping. This method is simple and has a constant time complexity. 

3. Convert Decimal Number to Octal Number

Problem Statement

Write a program to convert a decimal number to its octal representation.

Input Format

  • First line: an integer n (decimal number)

Output Format

  • Print "Octal representation of <n> is: <octal>"

Sample Input

148

Sample Output

Octal representation of 148 is: 224

Solutions

C

#include <stdio.h>

void convertToOctal(int num) {
    if (num == 0) {
        printf("0");
        return;
    }
    int octal[32], i = 0;

    while (num > 0) {
        octal[i] = num % 8;
        num /= 8;
        i++;
    }

    // Print octal in reverse order
    for (int j = i - 1; j >= 0; j--) {
        printf("%d", octal[j]);
    }
}

int main() {
    int n;
    scanf("%d", &n);
    printf("Octal representation of %d is: ", n);
    convertToOctal(n);
    printf("\n");
    return 0;
}

C++

#include <iostream>
using namespace std;

void convertToOctal(int num) {
    if (num == 0) {
        cout << "0";
        return;
    }
    int octal[32];
    int i = 0;

    while (num > 0) {
        octal[i] = num % 8;
        num /= 8;
        i++;
    }

    // Print octal in reverse order
    for (int j = i - 1; j >= 0; j--) {
        cout << octal[j];
    }
}

int main() {
    int n;
    cin >> n;
    cout << "Octal representation of " << n << " is: ";
    convertToOctal(n);
    cout << endl;
    return 0;
}

Java

import java.util.Scanner;

public class DecimalToOctal {
    public static void convertToOctal(int num) {
        if (num == 0) {
            System.out.print("0");
            return;
        }
        StringBuilder octal = new StringBuilder();

        while (num > 0) {
            octal.append(num % 8);
            num /= 8;
        }

        System.out.print(octal.reverse().toString());
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.print("Octal representation of " + n + " is: ");
        convertToOctal(n);
        System.out.println();
        scanner.close();
    }
}

Python

def convert_to_octal(num):
    if num == 0:
        return "0"
    octal = []
    while num > 0:
        octal.append(str(num % 8))
        num //= 8
    octal.reverse()
    return ''.join(octal)

n = int(input())
octal_representation = convert_to_octal(n)
print(f"Octal representation of {n} is: {octal_representation}")

Explanation of Code

The process is similar to binary conversion, the program keeps dividing the number by 8 and collects the remainders for the octal digits. The digits are reversed and printed. The time complexity is O(log n). 

4. Convert Decimal Number to Hexadecimal Number

Problem Statement

Write a program to convert a decimal number to its hexadecimal representation.

Input Format

  • First line: an integer n (decimal number)

Output Format

  • Print "Hexadecimal representation of <n> is: <hex>"

Sample Input

1457

Sample Output

Hexadecimal representation of 1457 is: 5B1

Solutions

C

#include <stdio.h>

void convertToHexadecimal(int num) {
    if (num == 0) {
        printf("0");
        return;
    }
    char hexa[100];
    int i = 0;

    while (num != 0) {
        int rem = num % 16;
        hexa[i++] = (rem < 10) ? (rem + '0') : (rem - 10 + 'A');
        num /= 16;
    }

    // Print hexadecimal in reverse order
    for (int j = i - 1; j >= 0; j--) {
        printf("%c", hexa[j]);
    }
}

int main() {
    int decimal;
    scanf("%d", &decimal);
    printf("Hexadecimal representation of %d is: ", decimal);
    convertToHexadecimal(decimal);
    printf("\n");
    return 0;
}

C++

#include <iostream>
using namespace std;

void convertToHexadecimal(int num) {
    if (num == 0) {
        cout << "0";
        return;
    }
    char hexa[100];
    int i = 0;

    while (num != 0) {
        int rem = num % 16;
        hexa[i++] = (rem < 10) ? (rem + '0') : (rem - 10 + 'A');
        num /= 16;
    }

    // Print hexadecimal in reverse order
    for (int j = i - 1; j >= 0; j--) {
        cout << hexa[j];
    }
}

int main() {
    int decimal;
    cin >> decimal;
    cout << "Hexadecimal representation of " << decimal << " is: ";
    convertToHexadecimal(decimal);
    cout << endl;
    return 0;
}

Java

import java.util.Scanner;

public class DecimalToHexadecimal {
    public static void convertToHexadecimal(int num) {
        if (num == 0) {
            System.out.print("0");
            return;
        }
        StringBuilder hexa = new StringBuilder();

        while (num != 0) {
            int rem = num % 16;
            if (rem < 10) {
                hexa.append(rem);
            } else {
                hexa.append((char) (rem - 10 + 'A'));
            }
            num /= 16;
        }

        System.out.print(hexa.reverse().toString());
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int decimal = scanner.nextInt();
        System.out.print("Hexadecimal representation of " + decimal + " is: ");
        convertToHexadecimal(decimal);
        System.out.println();
        scanner.close();
    }
}

Python

def convert_to_hexadecimal(num):
    if num == 0:
        return "0"
    hexa = []
    while num > 0:
        rem = num % 16
        if rem < 10:
            hexa.append(str(rem))
        else:
            hexa.append(chr(rem - 10 + ord('A')))
        num //= 8
    hexa.reverse()
    return ''.join(hexa)

decimal = int(input())
hexadecimal_representation = convert_to_hexadecimal(decimal)
print(f"Hexadecimal representation of {decimal} is: {hexadecimal_representation}")

Explanation of Code

The program repeatedly divides by 16 and uses the remainders to get hex digits (0-9, A-F for 10-15). The digits are collected, reversed, and printed. The time complexity is O(log n). 

Note: In the Python code provided originally, there was a typo (num //= 8 instead of 16); corrected here to //= 16.

5. Swap Two Numbers Without Using a Third Variable

Problem Statement

Write a program to swap two numbers without using a temporary variable.

Input Format

  • First line: an integer a
  • Second line: an integer b

Output Format

  • Print "Before swapping: a = , b = "
  • Print "After swapping: a = , b = "

Sample Input

5

10

Sample Output

Before swapping: a = 5, b = 10

After swapping: a = 10, b = 5

Solutions

C

#include <stdio.h>

int main() {
    int a, b;
    scanf("%d", &a);
    scanf("%d", &b);

    printf("Before swapping: a = %d, b = %d\n", a, b);

    // Swap without using a temporary variable
    a = a + b;
    b = a - b;
    a = a - b;

    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}

C++

#include <iostream>
using namespace std;

int main() {
    int a, b;
    cin >> a >> b;

    cout << "Before swapping: a = " << a << ", b = " << b << endl;

    // Swap without using a temporary variable
    a = a + b;
    b = a - b;
    a = a - b;

    cout << "After swapping: a = " << a << ", b = " << b << endl;
    return 0;
}

Java

import java.util.Scanner;

public class SwapNumbersWithoutTemp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        int a = scanner.nextInt();
        int b = scanner.nextInt();

        System.out.println("Before swapping: a = " + a + ", b = " + b);

        // Swap without using a temporary variable
        a = a + b;
        b = a - b;
        a = a - b;

        System.out.println("After swapping: a = " + a + ", b = " + b);
        scanner.close();
    }
}

Python

a = int(input())
b = int(input())

print("Before swapping: a =", a)
print("Before swapping: b =", b)

# Swap without using a temporary variable
a = a + b
b = a - b
a = a - b

print("After swapping: a =", a)
print("After swapping: b =", b)

Explanation of Code

The program uses arithmetic operations (addition and subtraction) to swap values without extra space. This works in O(1) time but may cause overflow for large numbers.

6. Convert Octal Number to Binary Number

Problem Statement

Write a program to convert an octal number to its binary representation.

Input Format

  • First line: an integer (octal number)

Output Format

  • Print "Binary representation: <binary>"

Sample Input

10

Sample Output

Binary representation: 1000

Solutions

C

#include <stdio.h>
#include <math.h>

int octalToDecimal(int octal) {
    int decimal = 0, base = 1;
    while (octal > 0) {
        int last_digit = octal % 10;
        decimal += last_digit * base;
        base *= 8;
        octal /= 10;
    }
    return decimal;
}

void decimalToBinary(int decimal) {
    if (decimal == 0) {
        printf("0");
        return;
    }
    int binary[32], i = 0;

    while (decimal > 0) {
        binary[i++] = decimal % 2;
        decimal /= 2;
    }

    // Print binary in reverse order
    for (int j = i - 1; j >= 0; j--) {
        printf("%d", binary[j]);
    }
}

int main() {
    int octal;
    scanf("%d", &octal);

    int decimal = octalToDecimal(octal);
    printf("Binary representation: ");
    decimalToBinary(decimal);
    printf("\n");
    return 0;
}

C++

#include <iostream>
using namespace std;

int octalToDecimal(int octal) {
    int decimal = 0, base = 1;
    while (octal > 0) {
        int last_digit = octal % 10;
        decimal += last_digit * base;
        base *= 8;
        octal /= 10;
    }
    return decimal;
}

void decimalToBinary(int decimal) {
    if (decimal == 0) {
        cout << "0";
        return;
    }
    int binary[32];
    int i = 0;

    while (decimal > 0) {
        binary[i++] = decimal % 2;
        decimal /= 2;
    }

    // Print binary in reverse order
    for (int j = i - 1; j >= 0; j--) {
        cout << binary[j];
    }
}

int main() {
    int octal;
    cin >> octal;

    int decimal = octalToDecimal(octal);
    cout << "Binary representation: ";
    decimalToBinary(decimal);
    cout << endl;
    return 0;
}

Java

import java.util.Scanner;

public class OctalToBinary {
    public static int octalToDecimal(int octal) {
        int decimal = 0, base = 1;
        while (octal > 0) {
            int lastDigit = octal % 10;
            decimal += lastDigit * base;
            base *= 8;
            octal /= 10;
        }
        return decimal;
    }

    public static void decimalToBinary(int decimal) {
        if (decimal == 0) {
            System.out.print("0");
            return;
        }
        StringBuilder binary = new StringBuilder();

        while (decimal > 0) {
            binary.append(decimal % 2);
            decimal /= 2;
        }
        System.out.print(binary.reverse().toString());
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int octal = scanner.nextInt();

        int decimal = octalToDecimal(octal);
        System.out.print("Binary representation: ");
        decimalToBinary(decimal);
        System.out.println();
        scanner.close();
    }
}

Python

def octal_to_decimal(octal):
    decimal = 0
    base = 1
    while octal > 0:
        last_digit = octal % 10
        decimal += last_digit * base
        base *= 8
        octal //= 10
    return decimal

def decimal_to_binary(decimal):
    if decimal == 0:
        return "0"
    binary = []
    while decimal > 0:
        binary.append(str(decimal % 2))
        decimal //= 2
    binary.reverse()
    return ''.join(binary)

octal_value = int(input())
decimal_value = octal_to_decimal(octal_value)
binary_value = decimal_to_binary(decimal_value)
print(f"Binary representation: {binary_value}")

Explanation of Code

The program first converts octal to decimal by multiplying digits with powers of 8, then converts decimal to binary as in question 2. Time complexity is O(log n) for each conversion.

7. Convert Octal Number to Decimal Number

Problem Statement

Write a program to convert an octal number to its decimal representation.

Input Format

  • First line: an integer (octal number)

Output Format

  • Print "Decimal representation: <decimal>"

Sample Input

10

Sample Output

Decimal representation: 8

Solutions

C

#include <stdio.h>
#include <math.h>

int octalToDecimal(int octal) {
    int decimal = 0, base = 1;
    while (octal > 0) {
        int last_digit = octal % 10;
        decimal += last_digit * base;
        base *= 8;
        octal /= 10;
    }
    return decimal;
}

int main() {
    int octal;
    scanf("%d", &octal);

    int decimal = octalToDecimal(octal);
    printf("Decimal representation: %d\n", decimal);
    return 0;
}

C++

#include <iostream>
using namespace std;

int octalToDecimal(int octal) {
    int decimal = 0, base = 1;
    while (octal > 0) {
        int last_digit = octal % 10;
        decimal += last_digit * base;
        base *= 8;
        octal /= 10;
    }
    return decimal;
}

int main() {
    int octal;
    cin >> octal;

    int decimal = octalToDecimal(octal);
    cout << "Decimal representation: " << decimal << endl;
    return 0;
}

Java

import java.util.Scanner;

public class OctalToDecimal {
    public static int octalToDecimal(int octal) {
        int decimal = 0, base = 1;
        while (octal > 0) {
            int lastDigit = octal % 10;
            decimal += lastDigit * base;
            base *= 8;
            octal /= 10;
        }
        return decimal;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int octal = scanner.nextInt();

        int decimal = octalToDecimal(octal);
        System.out.println("Decimal representation: " + decimal);
        scanner.close();
    }
}

Python

def octal_to_decimal(octal):
    decimal = 0
    base = 1
    while octal > 0:
        last_digit = octal % 10
        decimal += last_digit * base
        base *= 8
        octal //= 10
    return decimal

octal_value = int(input())
decimal_value = octal_to_decimal(octal_value)
print(f"Decimal representation: {decimal_value}")

Explanation of Code

The decimal is found by the program as it adds each octal digit times the corresponding power of 8 which is increasing. The time complexity is O(log n). 

8. Spiral Traversal of a Matrix

Problem Statement

Write a program to print the spiral traversal of a given matrix.

Input Format

  • First line: two integers ROW COL
  • Next ROW lines: COL integers each for the matrix

Output Format

  • Print "Spiral traversal of the matrix is: " followed by the elements in spiral order separated by space

Sample Input

4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Sample Output

Spiral traversal of the matrix is: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Solutions

C

#include <stdio.h>

int main() {
    int ROW, COL;
    scanf("%d %d", &ROW, &COL);
    int arr[100][100]; // Assuming max 100x100
    for (int i = 0; i < ROW; i++) {
        for (int j = 0; j < COL; j++) {
            scanf("%d", &arr[i][j]);
        }
    }

    printf("Spiral traversal of the matrix is: ");
    int top = 0, bottom = ROW - 1, left = 0, right = COL - 1;

    while (left <= right && top <= bottom) {
        for (int i = left; i <= right; i++)
            printf("%d ", arr[top][i]);
        top++;

        for (int i = top; i <= bottom; i++)
            printf("%d ", arr[i][right]);
        right--;

        if (top <= bottom) {
            for (int i = right; i >= left; i--)
                printf("%d ", arr[bottom][i]);
            bottom--;
        }

        if (left <= right) {
            for (int i = bottom; i >= top; i--)
                printf("%d ", arr[i][left]);
            left++;
        }
    }
    printf("\n");
    return 0;
}

C++

#include <iostream>
using namespace std;

int main() {
    int ROW, COL;
    cin >> ROW >> COL;
    int arr[100][100]; // Assuming max 100x100
    for (int i = 0; i < ROW; i++) {
        for (int j = 0; j < COL; j++) {
            cin >> arr[i][j];
        }
    }

    cout << "Spiral traversal of the matrix is: ";
    int top = 0, bottom = ROW - 1, left = 0, right = COL - 1;

    while (left <= right && top <= bottom) {
        for (int i = left; i <= right; i++)
            cout << arr[top][i] << " ";
        top++;

        for (int i = top; i <= bottom; i++)
            cout << arr[i][right] << " ";
        right--;

        if (top <= bottom) {
            for (int i = right; i >= left; i--)
                cout << arr[bottom][i] << " ";
            bottom--;
        }

        if (left <= right) {
            for (int i = bottom; i >= top; i--)
                cout << arr[i][left] << " ";
            left++;
        }
    }
    cout << endl;
    return 0;
}

Java

import java.util.Scanner;

public class SpiralTraversal {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int ROW = scanner.nextInt();
        int COL = scanner.nextInt();
        int[][] matrix = new int[ROW][COL];
        for (int i = 0; i < ROW; i++) {
            for (int j = 0; j < COL; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }

        System.out.print("Spiral traversal of the matrix is: ");
        int top = 0, bottom = ROW - 1, left = 0, right = COL - 1;

        while (left <= right && top <= bottom) {
            for (int i = left; i <= right; i++)
                System.out.print(matrix[top][i] + " ");
            top++;

            for (int i = top; i <= bottom; i++)
                System.out.print(matrix[i][right] + " ");
            right--;

            if (top <= bottom) {
                for (int i = right; i >= left; i--)
                    System.out.print(matrix[bottom][i] + " ");
                bottom--;
            }

            if (left <= right) {
                for (int i = bottom; i >= top; i--)
                    System.out.print(matrix[i][left] + " ");
                left++;
            }
        }
        System.out.println();
        scanner.close();
    }
}

Python

rows, cols = map(int, input().split())
matrix = []
for _ in range(rows):
    matrix.append(list(map(int, input().split())))

print("Spiral traversal of the matrix is:", end=" ")
top, bottom = 0, rows - 1
left, right = 0, cols - 1
result = []

while left <= right and top <= bottom:
    for i in range(left, right + 1):
        result.append(str(matrix[top][i]))
    top += 1

    for i in range(top, bottom + 1):
        result.append(str(matrix[i][right]))
    right -= 1

    if top <= bottom:
        for i in range(right, left - 1, -1):
            result.append(str(matrix[bottom][i]))
        bottom -= 1

    if left <= right:
        for i in range(bottom, top - 1, -1):
            result.append(str(matrix[i][left]))
        left += 1

print(' '.join(result))

Explanation of Code

While moving through layers the boundaries (top, bottom, left, right) are getting smaller: right, down, left, up. The conditions eliminate overlapping in odd-sized matrices, thus the spiral order is obtained in O(m*n) time. 

9. Print First N Fibonacci Numbers

Problem Statement

In financial modeling for compound interest projections, generate the first N Fibonacci numbers to simulate growth patterns in a sequence.

Sample Input

10

Sample Output

0 1 1 2 3 5 8 13 21 34

Solutions

C

#include <stdio.h>

void printFibonacci(int n) {
    int a = 0, b = 1, c;
    for (int i = 0; i < n; i++) {
        printf("%d ", a);
        c = a + b;
        a = b;
        b = c;
    }
}

int main() {
    int n;
    scanf("%d", &n);
    printFibonacci(n);
    printf("\n");
    return 0;
}

C++

#include <iostream>
using namespace std;

void printFibonacci(int n) {
    int a = 0, b = 1, c;
    for (int i = 0; i < n; i++) {
        cout << a << " ";
        c = a + b;
        a = b;
        b = c;
    }
}

int main() {
    int n;
    cin >> n;
    printFibonacci(n);
    cout << endl;
    return 0;
}

Java

import java.util.Scanner;

public class Fibonacci {
    public static void printFibonacci(int n) {
        int a = 0, b = 1, c;
        for (int i = 0; i < n; i++) {
            System.out.print(a + " ");
            c = a + b;
            a = b;
            b = c;
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        printFibonacci(n);
        System.out.println();
        scanner.close();
    }
}

Python

def print_fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=" ")
        a, b = b, a + b

n = int(input())
print_fibonacci(n)
print()

Explanation of Code

Starts with 0 and 1, each subsequent number is the sum of the previous two, printed iteratively. Efficient O(n) space and time, avoiding recursion depth issues.

10. Find the First Non-Repeating Character from a Stream of Characters

Problem Statement

In log analysis for error detection, process a stream of characters (string) to find the first unique character that doesn't repeat, indicating a rare event.

Sample Input

swiss

Sample Output

First non-repeating character: w

Solutions

C

#include <stdio.h>
#include <string.h>

char firstNonRepeating(char *str) {
    int count[256] = {0};
    for (int i = 0; str[i]; i++) {
        count[str[i]]++;
    }
    for (int i = 0; str[i]; i++) {
        if (count[str[i]] == 1) {
            return str[i];
        }
    }
    return '\0';
}

int main() {
    char str[100];
    scanf("%s", str);
    char result = firstNonRepeating(str);
    if (result) {
        printf("First non-repeating character: %c\n", result);
    } else {
        printf("No non-repeating character found.\n");
    }
    return 0;
}

C++

#include <iostream>
#include <unordered_map>
using namespace std;

char firstNonRepeating(string str) {
    unordered_map<char, int> count;
    for (char c : str) {
        count[c]++;
    }
    for (char c : str) {
        if (count[c] == 1) {
            return c;
        }
    }
    return '\0';
}

int main() {
    string str;
    cin >> str;
    char result = firstNonRepeating(str);
    if (result != '\0') {
        cout << "First non-repeating character: " << result << endl;
    } else {
        cout << "No non-repeating character found." << endl;
    }
    return 0;
}

Java

import java.util.HashMap;
import java.util.Scanner;

public class FirstNonRepeating {
    public static char firstNonRepeating(String str) {
        HashMap<Character, Integer> countMap = new HashMap<>();
        for (char c : str.toCharArray()) {
            countMap.put(c, countMap.getOrDefault(c, 0) + 1);
        }
        for (char c : str.toCharArray()) {
            if (countMap.get(c) == 1) {
                return c;
            }
        }
        return '\0';
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        char result = firstNonRepeating(str);
        if (result != '\0') {
            System.out.println("First non-repeating character: " + result);
        } else {
            System.out.println("No non-repeating character found.");
        }
        scanner.close();
    }
}

Python

def first_non_repeating(s):
    count = {}
    for char in s:
        count[char] = count.get(char, 0) + 1
    for char in s:
        if count[char] == 1:
            return char
    return None

s = input()
result = first_non_repeating(s)
if result:
    print("First non-repeating character:", result)
else:
    print("No non-repeating character found.")

Explanation of Code

Counts frequency with a map/array, then scans again to find the first with count 1. O(n) time, O(1) space for fixed charset.

11. Remove Duplicates from Sorted Array

Problem Statement

In data cleanup for a sorted list of user IDs, remove duplicates in-place to maintain a unique sequence for database deduplication.

Sample Input

0 0 1 1 2 2 3 4

Sample Output

0 1 2 3 4

Solutions

C

#include <stdio.h>

int removeDuplicates(int arr[], int n) {
    if (n == 0) return 0;
    int j = 0;
    for (int i = 1; i < n; i++) {
        if (arr[i] != arr[j]) {
            j++;
            arr[j] = arr[i];
        }
    }
    return j + 1;
}

int main() {
    int n = 8;
    int arr[8];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    int new_n = removeDuplicates(arr, n);
    for (int i = 0; i < new_n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    return 0;
}

C++

#include <iostream>
#include <vector>
using namespace std;

int removeDuplicates(vector<int>& nums) {
    if (nums.empty()) return 0;
    int j = 0;
    for (int i = 1; i < nums.size(); i++) {
        if (nums[i] != nums[j]) {
            j++;
            nums[j] = nums[i];
        }
    }
    return j + 1;
}

int main() {
    vector<int> nums(8);
    for (int i = 0; i < 8; i++) {
        cin >> nums[i];
    }
    int new_n = removeDuplicates(nums);
    for (int i = 0; i < new_n; i++) {
        cout << nums[i] << " ";
    }
    cout << endl;
    return 0;
}

Java

import java.util.Scanner;

public class RemoveDuplicates {
    public static int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        int j = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[j]) {
                j++;
                nums[j] = nums[i];
            }
        }
        return j + 1;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] nums = new int[8];
        for (int i = 0; i < 8; i++) {
            nums[i] = scanner.nextInt();
        }
        int n = removeDuplicates(nums);
        for (int i = 0; i < n; i++) {
            System.out.print(nums[i] + " ");
        }
        System.out.println();
        scanner.close();
    }
}

Python

def remove_duplicates(nums):
    if not nums:
        return 0
    j = 0
    for i in range(1, len(nums)):
        if nums[i] != nums[j]:
            j += 1
            nums[j] = nums[i]
    return j + 1

nums = list(map(int, input().split()))
n = remove_duplicates(nums)
print(' '.join(map(str, nums[:n])))

Explanation of Code

Uses two pointers: one tracks unique position (j), advances and overwrites when new value found. Leverages sorted order for O(n) efficiency.

12. Check if a Number is Palindrome

Problem Statement

In a banking system, verify if a transaction ID (read as a number) reads the same forwards and backwards to detect data entry errors during reconciliation.

Sample Input

12321

Sample Output

Yes

Solutions

C

#include <stdio.h>

int isPalindrome(int num) {
    int original = num, reversed = 0;
    while (num > 0) {
        reversed = reversed * 10 + num % 10;
        num /= 10;
    }
    return original == reversed;
}

int main() {
    int n;
    scanf("%d", &n);
    if (isPalindrome(n)) {
        printf("Yes\n");
    } else {
        printf("No\n");
    }
    return 0;
}

C++

#include <iostream>
using namespace std;

bool isPalindrome(int num) {
    int original = num, reversed = 0;
    while (num > 0) {
        reversed = reversed * 10 + num % 10;
        num /= 10;
    }
    return original == reversed;
}

int main() {
    int n;
    cin >> n;
    if (isPalindrome(n)) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
    return 0;
}

Java

import java.util.Scanner;

public class PalindromeNumber {
    public static boolean isPalindrome(int num) {
        int original = num, reversed = 0;
        while (num > 0) {
            reversed = reversed * 10 + num % 10;
            num /= 10;
        }
        return original == reversed;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        if (isPalindrome(n)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
        scanner.close();
    }
}

Python

def is_palindrome(num):
    original = num
    reversed_num = 0
    while num > 0:
        reversed_num = reversed_num * 10 + num % 10
        num //= 10
    return original == reversed_num

n = int(input())
if is_palindrome(n):
    print("Yes")
else:
    print("No")

Explanation of Code

The code reverses the number by extracting digits via modulo and division, then compares to the original. Handles positive integers in O(log n) time; assumes no leading zeros.

13. Find Factorial of a Number

Problem Statement

In a combinatorics calculator for scheduling shifts, compute the factorial of employee count to determine possible arrangements without repetition.

Sample Input

5

Sample Output

120

Solutions

C

#include <stdio.h>

long long factorial(int n) {
    if (n == 0) return 1;
    long long fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

int main() {
    int n;
    scanf("%d", &n);
    printf("%lld\n", factorial(n));
    return 0;
}

C++

#include <iostream>
using namespace std;

long long factorial(int n) {
    if (n == 0) return 1;
    long long fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

int main() {
    int n;
    cin >> n;
    cout << factorial(n) << endl;
    return 0;
}

Java

import java.util.Scanner;

public class Factorial {
    public static long factorial(int n) {
        if (n == 0) return 1;
        long fact = 1;
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
        return fact;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.println(factorial(n));
        scanner.close();
    }
}

Python

def factorial(n):
    if n == 0:
        return 1
    fact = 1
    for i in range(1, n + 1):
        fact *= i
    return fact

n = int(input())
print(factorial(n))

Explanation of Code

Iteratively multiplies numbers from 1 to n, handling base case 0! = 1. Uses long long in C/C++ for larger values; time O(n), may overflow for big n.

14. Check if a Number is Prime

Problem Statement

In cryptography key generation, check if a candidate number is prime to ensure secure prime factors for encryption algorithms.

Sample Input

17

Sample Output

Yes

Solutions

C

#include <stdio.h>
#include <math.h>

int isPrime(int n) {
    if (n <= 1) return 0;
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) return 0;
    }
    return 1;
}

int main() {
    int n;
    scanf("%d", &n);
    if (isPrime(n)) {
        printf("Yes\n");
    } else {
        printf("No\n");
    }
    return 0;
}

C++

#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) return false;
    }
    return true;
}

int main() {
    int n;
    cin >> n;
    if (isPrime(n)) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
    return 0;
}

Java

import java.util.Scanner;

public class PrimeCheck {
    public static boolean isPrime(int n) {
        if (n <= 1) return false;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        if (isPrime(n)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
        scanner.close();
    }
}

Python

import math

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

n = int(input())
if is_prime(n):
    print("Yes")
else:
    print("No")

Explanation of Code

Checks divisibility up to sqrt(n) for efficiency. Returns Yes/No based on no divisors found other than 1 and itself. Time O(sqrt(n)).

15. Reverse a String

Problem Statement

In text processing for a chat app, reverse user messages to create a fun "mirror" effect before sending to recipients.

Sample Input

hello

Sample Output

olleh

Solutions

C

#include <stdio.h>
#include <string.h>

void reverseString(char str[]) {
    int len = strlen(str);
    for (int i = 0; i < len / 2; i++) {
        char temp = str[i];
        str[i] = str[len - i - 1];
        str[len - i - 1] = temp;
    }
}

int main() {
    char str[100];
    scanf("%s", str);
    reverseString(str);
    printf("%s\n", str);
    return 0;
}

C++

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    string str;
    cin >> str;
    reverse(str.begin(), str.end());
    cout << str << endl;
    return 0;
}

Java

import java.util.Scanner;

public class ReverseString {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        StringBuilder reversed = new StringBuilder(str).reverse();
        System.out.println(reversed);
        scanner.close();
    }
}

Python

s = input()
reversed_s = s[::-1]
print(reversed_s)

Explanation of Code

Swaps characters from ends moving inward (C), or uses built-in reverse (others). O(n) time, in-place for C.

16. Find Largest Element in an Array

Problem Statement

In sensor data monitoring, identify the maximum reading from an array of temperature values to trigger alerts if above threshold.

Sample Input

5

10 20 15 30 25

Sample Output

30

Solutions

C

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    int max = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) max = arr[i];
    }
    printf("%d\n", max);
    return 0;
}

C++

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int n;
    cin >> n;
    int arr[100];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    int max_val = *max_element(arr, arr + n);
    cout << max_val << endl;
    return 0;
}

Java

import java.util.Scanner;

public class LargestElement {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }
        int max = arr[0];
        for (int i = 1; i < n; i++) {
            if (arr[i] > max) max = arr[i];
        }
        System.out.println(max);
        scanner.close();
    }
}

Python

n = int(input())
arr = list(map(int, input().split()))
print(max(arr))

Explanation of Code

Iterates through array tracking max value, or uses built-in max. O(n) time.

17. Count Vowels in a String

Problem Statement

In a sentiment analysis tool, count vowels in customer feedback text to gauge emotional tone based on vowel frequency.

Sample Input

hello

Sample Output

2

Solutions

C

#include <stdio.h>
#include <string.h>

int countVowels(char str[]) {
    int count = 0;
    for (int i = 0; str[i]; i++) {
        char c = tolower(str[i]);
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') count++;
    }
    return count;
}

int main() {
    char str[100];
    scanf("%s", str);
    printf("%d\n", countVowels(str));
    return 0;
}

C++

#include <iostream>
#include <string>
using namespace std;

int countVowels(string str) {
    int count = 0;
    for (char c : str) {
        c = tolower(c);
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') count++;
    }
    return count;
}

int main() {
    string str;
    cin >> str;
    cout << countVowels(str) << endl;
    return 0;
}

Java

import java.util.Scanner;

public class CountVowels {
    public static int countVowels(String str) {
        int count = 0;
        str = str.toLowerCase();
        for (char c : str.toCharArray()) {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') count++;
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        System.out.println(countVowels(str));
        scanner.close();
    }
}

Python

s = input().lower()
vowels = 'aeiou'
count = sum(1 for char in s if char in vowels)
print(count)

Explanation of Code

Converts to lowercase, counts occurrences of a/e/i/o/u. O(n) time.

18. Linear Search in Array

Problem Statement

In inventory lookup, search for a product ID in a list of stocked items to check availability.

Sample Input

5

10 20 30 40 50

30

Sample Output

Found at index 2

Solutions

C

#include <stdio.h>

int linearSearch(int arr[], int n, int key) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == key) return i;
    }
    return -1;
}

int main() {
    int n;
    scanf("%d", &n);
    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    int key;
    scanf("%d", &key);
    int index = linearSearch(arr, n, key);
    if (index != -1) {
        printf("Found at index %d\n", index);
    } else {
        printf("Not found\n");
    }
    return 0;
}

C++

#include <iostream>
using namespace std;

int linearSearch(int arr[], int n, int key) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == key) return i;
    }
    return -1;
}

int main() {
    int n;
    cin >> n;
    int arr[100];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    int key;
    cin >> key;
    int index = linearSearch(arr, n, key);
    if (index != -1) {
        cout << "Found at index " << index << endl;
    } else {
        cout << "Not found" << endl;
    }
    return 0;
}

Java

import java.util.Scanner;

public class LinearSearch {
    public static int linearSearch(int[] arr, int key) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) return i;
        }
        return -1;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }
        int key = scanner.nextInt();
        int index = linearSearch(arr, key);
        if (index != -1) {
            System.out.println("Found at index " + index);
        } else {
            System.out.println("Not found");
        }
        scanner.close();
    }
}

Python

n = int(input())
arr = list(map(int, input().split()))
key = int(input())
index = -1
for i in range(n):
    if arr[i] == key:
        index = i
        break
if index != -1:
    print(f"Found at index {index}")
else:
    print("Not found")

Explanation of Code

Scans array sequentially until key matches, returns index or -1. O(n) time worst case.

19. Bubble Sort on Array

Problem Statement

In report generation, sort employee performance scores in ascending order using simple swaps for small datasets.

Sample Input

5

64 34 25 12 22

Sample Output

12 22 25 34 64

Solutions

C

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int n;
    scanf("%d", &n);
    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    bubbleSort(arr, n);
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    return 0;
}

C++

#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

int main() {
    int n;
    cin >> n;
    int arr[100];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    bubbleSort(arr, n);
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}

Java

import java.util.Scanner;

public class BubbleSort {
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }
        bubbleSort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
        scanner.close();
    }
}

Python

n = int(input())
arr = list(map(int, input().split()))
for i in range(n - 1):
    for j in range(n - i - 1):
        if arr[j] > arr[j + 1]:
            arr[j], arr[j + 1] = arr[j + 1], arr[j]
print(' '.join(map(str, arr)))

Explanation of Code

Repeatedly swaps adjacent elements if out of order, bubbling largest to end each pass. O(n^2) time.

20. Armstrong Number Check

Problem Statement

In a puzzle game app, check if a player's score is an Armstrong number (sum of cubes of digits equals itself) to award bonus points.

Sample Input

153

Sample Output

Yes

Solutions

C

#include <stdio.h>
#include <math.h>

int isArmstrong(int num) {
    int original = num, sum = 0, digits = 0;
    int temp = num;
    while (temp > 0) {
        digits++;
        temp /= 10;
    }
    temp = num;
    while (temp > 0) {
        sum += pow(temp % 10, digits);
        temp /= 10;
    }
    return sum == original;
}

int main() {
    int n;
    scanf("%d", &n);
    if (isArmstrong(n)) {
        printf("Yes\n");
    } else {
        printf("No\n");
    }
    return 0;
}

C++

#include <iostream>
#include <cmath>
using namespace std;

bool isArmstrong(int num) {
    int original = num, sum = 0, digits = 0;
    int temp = num;
    while (temp > 0) {
        digits++;
        temp /= 10;
    }
    temp = num;
    while (temp > 0) {
        sum += pow(temp % 10, digits);
        temp /= 10;
    }
    return sum == original;
}

int main() {
    int n;
    cin >> n;
    if (isArmstrong(n)) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
    return 0;
}

Java

import java.util.Scanner;

public class ArmstrongCheck {
    public static boolean isArmstrong(int num) {
        int original = num, sum = 0, digits = 0;
        int temp = num;
        while (temp > 0) {
            digits++;
            temp /= 10;
        }
        temp = num;
        while (temp > 0) {
            sum += Math.pow(temp % 10, digits);
            temp /= 10;
        }
        return sum == original;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        if (isArmstrong(n)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
        scanner.close();
    }
}

Python

import math

def is_armstrong(num):
    original = num
    digits = len(str(num))
    sum_val = 0
    while num > 0:
        sum_val += math.pow(num % 10, digits)
        num //= 10
    return sum_val == original

n = int(input())
if is_armstrong(n):
    print("Yes")
else:
    print("No")

Explanation of Code

Counts digits, sums each digit raised to digit count power, compares to original. O(log n) time.

Programming Languages and Code Implementation

The programming language that you use can make a big difference in your performance when you are getting ready for coding interviews or taking part in competitive programming challenges. Various companies and platforms accept different languages, and it is necessary that you know some of the most frequently used ones. Here we will examine the programming languages that are typically the case in coding interviews, particularly for companies like Infosys, and talk about how these languages can be used to solve problems in data structures and algorithms (DSA), DBMS, etc.

C and C++

C and C++ are foundational languages that have been staples in competitive coding and algorithm-based challenges for years. They are known for their high performance, efficient memory management, and flexibility.

  • C: Great for low-level programming and control over system resources. In competitive coding, C is often chosen for its simplicity and fast execution. Problems involving data structures like arrays, linked lists, or trees can be solved effectively in C.
  • C++: This language builds on C and adds features such as object-oriented programming (OOP), STL (Standard Template Library), and automatic memory management. In competitive coding, C++ is widely used due to its built-in data structures like vectors, sets, and maps, which simplify many coding problems. It's also one of the most common languages for solving DSA problems in coding interviews.

Java

Java is a highly popular programming language in both enterprise-level applications and coding interviews. Known for its portability and ease of use, Java is commonly used in companies like Infosys for coding interviews.

Java’s built-in libraries like ArrayList, HashMap, and LinkedList provide efficient solutions for data manipulation. Its object-oriented nature allows for modular code, and it offers automatic garbage collection, making memory management easier for developers. In coding interviews, problems involving object-oriented programming (OOP) concepts, inheritance, and polymorphism can be solved effectively using Java.

Python

Python has become very popular mainly because of its simplicity and user-friendliness, hence it is a perfect language for competitive coding and interview problems. With Python being less confusing, developers can concentrate more on problem-solving than the language syntax. It is particularly great for coding up data structure and algorithm problems fast.

Python also has strong support for data manipulation libraries, like NumPy and Pandas, and has built-in functions for sorting, searching, and other common tasks. It’s widely used in coding rounds, especially for problems that involve graphs, dynamic programming (DP), or greedy algorithms.

SQL

In many coding interviews, especially those focusing on DBMS (Database Management Systems), candidates are expected to demonstrate their SQL skills. SQL is used to query, update, and manage relational databases. In coding problems, you may be asked to perform tasks such as retrieving subsets of data, joining tables, or filtering information based on certain conditions.

Competitive Coding and DSA

For competitive coding, it is usually expected that candidates are highly skilled in C, C++, Java, and Python. These languages are typically employed in the resolution of DSA (Data Structures and Algorithms) problems, examples of which are sorting algorithms, graph traversal and searching algorithms. It is very important to know the time and space complexities of the algorithms and also how to implement them efficiently in these languages.

Sample Coding Questions with Solutions

Practice is essential for cracking coding interviews. Below, we provide a couple of representative coding questions often asked in coding rounds, along with solutions to help you understand the expected approach and reasoning.

Problem 1: Subset Sum Problem

Problem Statement:
Given a set of non-negative integers and a target sum, determine if there is a subset of the given set whose sum is equal to the target sum.

  • Input: A set of integers (e.g., {3, 34, 4, 12, 5, 2}) and a target sum (e.g., 9).
  • Output: True if there is a subset whose sum equals the target, otherwise False.
Solution:

This problem can be solved using dynamic programming (DP). We maintain a 2D DP table where each entry dp[i][j] represents whether there is a subset of the first i elements of the set that sums to j. If we find dp[n][target] to be True, we know that a subset exists.

def subset_sum(nums, target):
    dp = [False] * (target + 1)  # Initialize DP array of size (target + 1), all set to False.
    dp[0] = True  # Base case: A sum of 0 is always achievable with an empty subset.
    
    for num in nums:  # Iterate over all numbers in the input list `nums`.
        for i in range(target, num - 1, -1):  # Iterate backwards from target to num (to prevent reuse of same element in this iteration).
            dp[i] = dp[i] or dp[i - num]  # If dp[i - num] is True, then dp[i] becomes True.
    
    return dp[target]  # Return True if dp[target] is True (indicating a subset with the given target sum exists).

# Example usage:
nums = [3, 34, 4, 12, 5, 2]  # List of numbers.
target = 9  # The target sum we're looking for.
print(subset_sum(nums, target))  # Output: True

Problem 2: Coding Round Example - Find the Subset

Problem Statement:
Given a given set of non-negative integers and a target sum, print all the subsets that sum up to the target sum.

Solution Approach:

We use a recursive approach to generate all subsets and check their sum. This will give us all possible subsets, and we will check if their sum matches the target.

def find_subsets(nums, target):
result = [] # This will store the final result (list of valid subsets).
def backtrack(start, path, target):
# Base case: if the remaining target is 0, we've found a valid subset
if target == 0:
result.append(path)
return
for i in range(start, len(nums)): # Iterate over the elements starting from 'start'
if nums[i] > target: # If the current element exceeds the target, skip it
continue
# Include the current element in the subset and reduce the target accordingly
backtrack(i + 1, path + [nums[i]], target - nums[i]) # Move to the next element
# Start the backtracking process from index 0, an empty path, and the given target
backtrack(0, [], target)
return result # Return the list of valid subsets
# Example usage:
nums = [3, 34, 4, 12, 5, 2] # List of numbers
target = 9 # The target sum
print(find_subsets(nums, target)) # Output: [[4, 5], [3, 4, 2]]

This solution uses backtracking to explore all subsets and keep track of the ones that match the target sum.

🎯 Calculate your GPA instantly — No formulas needed!!

Infosys Previous Year Coding Questions

Over the years, Infosys has maintained a pattern where candidates encounter coding problems ranging from easy to hard difficulty levels. These coding questions asked in Infosys online test primarily test problem-solving ability, data structures, algorithms, and optimisation techniques. Practicing previous-year question patterns can help you understand the level of complexity and improve your approach during the actual assessment and strengthen your Infosys coding preparation.

Let’s dive into Infosys most asked coding questions:

1. Monster Defeat Sequence

Problem Statement

You are given N monsters, where each monster requires a certain amount of experience points to defeat. Once defeated, the monster rewards you with additional experience points.

Initially, you have X experience points. Determine whether it is possible to defeat all monsters by choosing an appropriate order.

Example

Input:

Initial Experience = 10

Monster Details:
Power  Bonus
5         4
15        10
8         3

Output:

YES

Explanation

  • Defeat the monster requiring 5 experience points and gain 4 points.
  • Experience becomes 14.
  • Defeat the monster requiring 8 experience points and gain 3 points.
  • Experience becomes 17.
  • Finally, defeat the monster requiring 15 experience points and gain 10 points.

Since all monsters can be defeated, the answer is YES.

Python Solution

n, x = map(int, input().split())
monsters = []
for _ in range(n):
   power, bonus = map(int, input().split())
   monsters.append((power, bonus))
monsters.sort()
possible = True
for power, bonus in monsters:
   if x < power:
       possible = False
       break
   x += bonus

print("YES" if possible else "NO")

Time Complexity

O(N log N) due to sorting.

2. Maximum XOR Value

Problem Statement

An array contains N elements, where N is even. You can choose at most N/2 numbers from the array.

Find the maximum possible XOR value obtained from the selected elements.

Example

Input

4
1 2 3 4

Output

7

Explanation

Selecting 3 and 4 gives:

3 XOR 4 = 7

which is the maximum obtainable value.

Approach

  • Explore different combinations.
  • Compute XOR values.
  • Keep track of the maximum value obtained.

Time Complexity

Brute-force approach:

O(2ᴺ)

Optimized approaches use bit manipulation and dynamic programming techniques.

3. Largest Meatball Problem

Problem Statement

A restaurant repeatedly cuts meatballs based on daily demand and reinserts the remaining portion back into the queue.

Given the initial sizes of meatballs and the number of operations performed, determine which meatball remains the largest at the end.

Example

Input

5
4 7 2 9 5

Output

9

Explanation

The largest meatball continues to remain the dominant piece after processing operations.

Approach

A max heap or priority queue can efficiently track the largest element after every operation.

Time Complexity

O(N log N)

4. Decimal to Binary Conversion

Problem Statement

Convert a decimal number into its binary representation.

Example

Input

13

Output

1101

Explanation

13 ÷ 2 = 6 remainder 1

6 ÷ 2 = 3 remainder 0

3 ÷ 2 = 1 remainder 1

1 ÷ 2 = 0 remainder 1

Reading the remainders in reverse order gives:

1101

Python Solution

num = int(input())
binary = ""
while num > 0:
   binary = str(num % 2) + binary
   num //= 2
print(binary)

Time Complexity

O(log N)

5. Swap Two Numbers Without Using a Temporary Variable

Problem Statement

Write a program to exchange two numbers without using a third variable.

Example

Input

a = 8
b = 5

Output

a = 5
b = 8

Python Solution

a, b = map(int, input().split())
a = a + b
b = a - b
a = a - b
print(a, b)

Time Complexity

O(1)

Key Topics Frequently Asked in Infosys Coding Rounds

Based on previous hiring patterns, Infosys commonly asks questions from the following areas:

  • Arrays
  • Strings
  • Sorting Algorithms
  • Greedy Algorithms
  • Dynamic Programming
  • Bit Manipulation
  • Trees and Graphs
  • Queues and Stacks
  • Mathematical Problems
  • Recursion

Preparing these topics and Infosys most asked coding questions thoroughly can significantly improve your chances of performing well in the Infosys coding assessment.

30-Day Infosys Coding Preparation Roadmap

Many candidates spend weeks solving random Infosys coding questions and still struggle during the actual coding round. The problem isn't a lack of practice, it's a lack of structured preparation. Instead of solving questions randomly, candidates should follow a systematic approach that gradually builds problem-solving skills while covering the concepts commonly assessed in Infosys coding rounds. The roadmap below is designed to help you practice Infosys coding questions strategically and improve your chances of performing well in the assessment.

Week 1: Build Problem-Solving Fundamentals

The first week should focus on developing logical thinking and coding speed rather than jumping directly into complex algorithms.

Day 1–2: Arrays and Basic Iteration

Practice:

  • Finding the largest and smallest elements
  • Second-largest element
  • Array rotation
  • Frequency counting
  • Missing number problems

Goal:
Learn to solve problems using loops and conditions without relying on advanced techniques.

Day 3–4: Strings and Pattern Recognition

Practice:

  • Palindrome checking
  • Anagram detection
  • String reversal
  • Character frequency analysis
  • Removing duplicates

Goal:
Strengthen your ability to process input efficiently and identify common string manipulation patterns.

Day 5–6: Mathematical and Logical Problems

Practice:

  • Prime number problems
  • Factorial variations
  • Number series
  • Digit manipulation
  • GCD and LCM problems

Goal:
Improve analytical thinking and become comfortable translating logic into code.

Day 7: Timed Practice Session

Attempt:

  • 5 Easy Problems
  • 3 Medium Problems

Time Limit:
90 Minutes

Focus:
Accuracy over speed.

Week 2: Master Core Data Structures

This week focuses on understanding how data can be stored and manipulated efficiently.

Day 8–10: Linked Lists

Practice:

  • Traversal
  • Insertion and deletion
  • Reversing a linked list
  • Finding the middle node

Goal:
Develop confidence in pointer-based problem solving.

Day 11–12: Stacks and Queues

Practice:

  • Balanced parentheses
  • Next greater element
  • Queue implementation
  • Stack-based expression evaluation

Goal:
Recognize scenarios where LIFO and FIFO structures simplify solutions.

Day 13–14: Hashing Techniques

Practice:

  • Duplicate detection
  • Frequency maps
  • Pair-sum problems
  • First non-repeating character

Goal:
Reduce brute-force solutions by using efficient lookups.

Week 3: Focus on Interview-Favourite Algorithms

Most medium-to-difficult Infosys questions test whether candidates can identify efficient approaches rather than write lengthy code.

Day 15–16: Searching and Sorting

Practice:

  • Binary search
  • Merge sort concepts
  • Sorting-based optimizations
  • Search in rotated arrays

Goal:
Understand when sorting can reduce complexity.

Day 17–18: Recursion and Backtracking

Practice:

  • Recursive pattern generation
  • Subset problems
  • Permutation generation

Goal:
Learn to break larger problems into smaller subproblems.

Day 19–21: Trees and Graphs

Practice:

  • Tree traversal
  • Binary tree height
  • BFS and DFS basics
  • Graph connectivity problems

Goal:
Become comfortable visualizing data relationships and traversal strategies.

Week 4: Crack Medium and Advanced Problems

The final week should simulate the pressure and complexity of the actual coding assessment.

Day 22–24: Dynamic Programming Foundations

Practice:

  • Fibonacci optimization
  • Climbing stairs
  • Coin change
  • Longest common subsequence

Goal:
Learn how to avoid repeated computations and improve efficiency.

Day 25–26: Greedy Algorithms

Practice:

  • Activity selection
  • Job scheduling
  • Minimum platforms
  • Resource allocation problems

Goal:
Understand when locally optimal choices lead to globally optimal solutions.

Day 27–28: Mixed Coding Challenges

Attempt problems involving:

  • Arrays + Hashing
  • Strings + Recursion
  • Trees + Dynamic Programming

Goal:
Build adaptability for unfamiliar questions.

Day 29: Full-Length Mock Assessment

Attempt:

  • Easy Question: 20 Minutes
  • Medium Question: 30 Minutes
  • Hard Question: 50 Minutes

Rules:

  • No external help
  • No solution lookup
  • Follow actual exam conditions

Day 30: Performance Analysis and Revision

Instead of solving new questions, review your entire preparation.

Analyse:

  • Topics where you made repeated mistakes
  • Questions that took excessive time
  • Common logical errors
  • Time-complexity issues

Create a personal revision sheet containing:

  • Important algorithms
  • Frequently used patterns
  • Common edge cases
  • Mistakes to avoid during the assessment

Pro Tip

A candidate who solves 80 carefully selected Infosys coding questions and thoroughly reviews mistakes often performs better than someone who rushes through 300 random problems. Instead of focusing solely on the number of questions solved, prioritise understanding patterns, optimizing solutions, and improving decision-making under time pressure to maximise your chances of success in the coding round.

Tips for Cracking Infosys Coding Round

If you want to clear an Infosys coding assessment, then you must follow these tips:

  • Your Infosys coding preparation should start with a strong understanding of basic concepts of algorithms and data structures.
  • You should practice Infosys coding questions daily on the platforms such as LeetCode or HackerRank for assessment.
  • Firstly, you should read the questions thoroughly, and then you can divide them into smaller parts for coding.
  • Concentrate more on the writing of the efficient code and also on the understanding of the time and space complexity.
  • By taking part in mock interviews, you can be sure and confident of the infosys coding interview questions

Conclusion

In conclusion, succeeding in the Infosys coding questions round requires a strong grasp of core concepts, consistent practice, and a strategic approach to preparation. Solving Infosys previous year coding questions can help you understand the patterns and difficulty level commonly seen in the assessment. Reviewing frequently asked Infosys coding interview questions is also useful for strengthening your problem-solving skills and improving your confidence. Additionally, practicing relevant Infosys coding exam questions and answers can familiarize you with the test format and help you perform better during the selection process. With the right preparation and persistence, you can confidently approach the Infosys hiring process and maximize your chances of success.

Why It Matters: In the tech world of 2025, proficiency in coding is the key to access jobs at Infosys that lead to innovation.

Practical Advice for Learners

  • Engage in coding practice every day on different platforms. 
  • Master multiple languages such as Python and Java. 
  • Take part in mock interviews to raise your level of confidence. 
  • Work out the time complexity to make your code efficient. 
  • Correct your mistakes for continuous improvement.
₹ 49,000
strip
₹ 33,000
/-
Karthik was able to transform his career from a boring job to an exciting job in software!
Talk to a career expert
intensive student
emoji

Frequently Asked Questions

1. What types of coding questions in Infosys interviews are considered the most challenging?

Questions involving dynamic programming and complex data structures are often seen as the most challenging.

2. How can I prepare for coding questions of Infosys?

Utilize online coding platforms, participate in coding competitions, and review past interview experiences shared by candidates.

3. What are the most important Infosys previous year coding questions to practice?

Some of the most frequently repeated Infosys previous year coding questions are based on arrays, strings, searching, sorting, hashing, and dynamic programming. Candidates should focus on pattern-based problems rather than memorizing solutions, as similar concepts often reappear with variations in the Infosys online coding test.

4. What coding questions are asked in the Infosys online test?

The coding questions asked in the Infosys online test usually range from easy to medium difficulty and evaluate problem-solving skills, data structures, algorithms, and optimization techniques. Common topics include arrays, strings, linked lists, recursion, sorting, and dynamic programming. The exact pattern may vary depending on the role and hiring requirements.

5. How can beginners start Infosys coding preparation effectively?

An effective Infosys coding preparation strategy starts with mastering fundamentals such as arrays, strings, and hashing before moving on to advanced topics like trees, graphs, and dynamic programming. Practicing timed mock tests, reviewing mistakes, and solving problems consistently are equally important for improving coding-round performance.

6. What are the most asked Infosys coding interview questions?

Some of the Infosys most asked coding questions involve palindrome checking, array rotation, finding duplicate elements, longest common subsequence, binary search, and linked list reversal. Interviewers may also assess a candidate's ability to optimise solutions and explain their approach clearly.

7. Are Infosys coding exam questions and answers enough to crack the interview?

Practicing Infosys coding exam questions and answers provides a strong foundation, but success in the interview also depends on understanding problem-solving approaches, time complexity, and writing optimized code. Candidates should combine coding practice with mock assessments and revision to improve their chances of clearing the Infosys coding interview.

Summarise With Ai
ChatGPT
Perplexity
Claude
Gemini
Gork
ChatGPT
Perplexity
Claude
Gemini
Gork
Chat with us
Chat with us
Talk to career expert