Back

Infosys Coding Questions and Answers: Tips to Crack

23 Oct 2024
3 min read

As one of the leading IT service companies, Infosys is known for its rigorous selection process, particularly for technical roles. Coding questions are critical to the evaluation process, testing candidates' problem-solving skills and coding proficiency. This article delves into the various coding questions asked in Infosys, by offering valuable tips for success.

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)

Top Coding Questions With Answers Asked in Infosys

Here, are the sample coding questions asked in the Infosys online test:

1. Write a Program to Swap Two Numbers

C

#include <stdio.h>

int main() {
    int a, b, temp;
    printf("Enter the first value: ");
    scanf("%d", &a);
    printf("Enter the second value: ");
    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;
}

Java

import java.util.Scanner;

public class SwapNumbers {
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter the first value: ");
        int a = scanner.nextInt();
        System.out.print("Enter the second value: ");
        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

# Swap two variables in Python
a = int(input("Enter the first value: "))
b = int(input("Enter the second value: "))

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)

2. Write a Program to Convert Decimal Number to Binary Number

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 = 11;
    printf("Binary representation of %d is: ", n);
    convertToBinary(n);
    printf("\n");
    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) {
        int n = 11;
        System.out.print("Binary representation of " + n + " is: ");
        convertToBinary(n);
        System.out.println();
    }
}

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 = 11
binary_representation = convert_to_binary(n)
print(f"Binary representation of {n} is: {binary_representation}")

3. Write a Program to Convert Decimal Number to Octal Number

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 = 148;
    printf("Octal representation of %d is: ", n);
    convertToOctal(n);
    printf("\n");
    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) {
        int n = 148;
        System.out.print("Octal representation of " + n + " is: ");
        convertToOctal(n);
        System.out.println();
    }
}

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 = 148
octal_representation = convert_to_octal(n)
print(f"Octal representation of {n} is: {octal_representation}")

4. Write a Program to Convert Decimal Number to Hexadecimal Number

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 = 1457;
    printf("Hexadecimal representation of %d is: ", decimal);
    convertToHexadecimal(decimal);
    printf("\n");
    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) {
        int decimal = 1457;
        System.out.print("Hexadecimal representation of " + decimal + " is: ");
        convertToHexadecimal(decimal);
        System.out.println();
    }
}

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 //= 16
    hexa.reverse()
    return ''.join(hexa)

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

5. Write a Program to Swap Two Numbers without Using a Third Variable

C

#include <stdio.h>

int main() {
    int a, b;
    printf("Enter the first value: ");
    scanf("%d", &a);
    printf("Enter the second value: ");
    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;
}

Java

import java.util.Scanner;

public class SwapNumbersWithoutTemp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter the first value: ");
        int a = scanner.nextInt();
        System.out.print("Enter the second value: ");
        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

# Swap two variables without a temporary variable
a = int(input("Enter the first value: "))
b = int(input("Enter the second value: "))

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)

6. Write a Program to Convert Octal Number to Binary Number

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;
    printf("Enter an octal number: ");
    scanf("%d", &octal);
 int decimal = octalToDecimal(octal);
    printf("Binary representation: ");
    decimalToBinary(decimal);
    printf("\n");
    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);
        System.out.print("Enter an octal number: ");
        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("Enter an octal number: "))
decimal_value = octal_to_decimal(octal_value)
binary_value = decimal_to_binary(decimal_value)
print(f"Binary representation: {binary_value}")

7. Write a Program to Convert Octal Number to Decimal Number

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;
    printf("Enter an octal number: ");
    scanf("%d", &octal);
 int decimal = octalToDecimal(octal);
    printf("Decimal representation: %d\n", decimal);
    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);
        System.out.print("Enter an octal number: ");
        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("Enter an octal number: "))
        decimal_value = octal_to_decimal(octal_value)
        print(f"Decimal representation: {decimal_value}")


8. Write a Program to Find the Spiral Traversal of a Matrix

C

#include <stdio.h>

#define ROW 4
#define COL 4

void spiralTraversal(int arr[ROW][COL]) {
    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++;
        }
}
}

int main() {
    int matrix[ROW][COL] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };

    printf("Spiral traversal of the matrix is: ");
    spiralTraversal(matrix);
    printf("\n");
    return 0;
}

Java

public class SpiralTraversal {
    public static void spiralTraversal(int[][] matrix) {
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 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++;
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 16}
        };

        System.out.print("Spiral traversal of the matrix is: ");
        spiralTraversal(matrix);
        System.out.println();
    }
}

Python

def spiral_traversal(matrix):
    result = []
    if not matrix:
        return result

    top, bottom = 0, len(matrix) - 1
    left, right = 0, len(matrix[0]) - 1

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

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

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

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

    return result

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]

print("Spiral traversal of the matrix is:", spiral_traversal(matrix))

9. Print First N Fibonacci Numbers

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 = 10; // Change this value for more Fibonacci numbers
    printFibonacci(n);
    return 0;
}

Java

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) {
        int n = 10; // Change this value for more Fibonacci numbers
        printFibonacci(n);
    }
}

Python

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

n = 10  # Change this value for more Fibonacci numbers
print_fibonacci(n)

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

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[] = "swiss";
    char result = firstNonRepeating(str);
    if (result) {
        printf("First non-repeating character: %c\n", result);
    } else {
        printf("No non-repeating character found.\n");
    }
    return 0;
}

Java

import java.util.HashMap;

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) {
        String str = "swiss";
        char result = firstNonRepeating(str);
        if (result != '\0') {
            System.out.println("First non-repeating character: " + result);
        } else {
            System.out.println("No non-repeating character found.");
        }
    }
}

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 = "swiss"
result = first_non_repeating(s)
if result:
    print("First non-repeating character:", result)
else:
    print("No non-repeating character found.")

11. Remove Duplicates from Sorted Array

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 arr[] = {0, 0, 1, 1, 2, 2, 3, 4};
    int n = sizeof(arr) / sizeof(arr[0]);
    n = removeDuplicates(arr, n);
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Java

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) {
        int[] nums = {0, 0, 1, 1, 2, 2, 3, 4};
        int n = removeDuplicates(nums);
        for (int i = 0; i < n; i++) {
            System.out.print(nums[i] + " ");
        }
    }
}

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 = [0, 0, 1, 1, 2, 2, 3, 4]
n = remove_duplicates(nums)
print(nums[:n])

Tips for Cracking Infosys Coding Round

Here are some tips to clear Infosys coding assessment:

  • Make sure you have a strong grasp of fundamental concepts in algorithms and data structures.
  • Practice regularly coding questions on platforms like LeetCode or HackerRank for Infosys.
  • Read questions carefully and break them down into smaller parts before coding.
  • Focus on writing efficient code and understanding the time and space complexity.
  • Participate in mock interviews to get comfortable with the interview format.

Conclusion

In conclusion, preparing for Infosys coding questions requires a combination of understanding core concepts, regular practice, and strategic preparation. By familiarizing yourself with the types of questions typically asked and following the tips provided, you can enhance your chances of success in the selection process.

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.

Read More Articles

Chat with us
Talk to career expert