Top 30 Infosys Coding Interview Questions and Answers
Infosys is one of the leading IT services companies globally and is renowned for its rigorous recruitment process, especially in coding and technical rounds. With over 300,000 employees across 50+ countries, Infosys emphasizes problem-solving skills and programming expertise when selecting candidates. The coding questions in their hiring process test logical reasoning, data structures, algorithms, and real-world problem-solving abilities. In this blog, we will discuss some of the commonly asked Infosys coding interview questions and answers and provide insightful answers to help you ace your interview.
Infosys Coding Interview Questions and Answers For Freshers
When preparing for an entry-level job position at Infosys, one of the key components of the interview process involves coding assessments. These assessments are designed to evaluate your problem-solving skills, understanding of algorithms, and coding proficiency. Below are Infosys coding interview questions and answers for freshers.
Q1. What will be the output of the Pseudo Code provided below?
#include <stdio.h>
int main()
{
float i;
i = 1;
printf("%f", i);
return 0;
}
Sample Answer: The given C code involves printing a floating-point value. The output of the provided C pseudo code will be:
1.000000
Explanation:
- The variable i is declared as a float and initialized with the value 1.
- The printf function is used to print the value of i. The format specifier %f is used, which is for printing floating-point numbers in C.
- In C, when a float is printed using %f, it prints the number with six digits after the decimal point by default.
So, when the value 1 is printed as a floating-point number, it is displayed as 1.000000 (with six decimal places). If you want to modify the precision of the printed number, you could adjust the format specifier (e.g., %.2f for two decimal places).


Q2. Write a C program to arrange the given number to form the biggest number.
Sample Answer: In this task, we need to write a C program that arranges a given set of numbers to form the largest possible number when concatenated. To achieve this, we treat the numbers as strings, allowing us to compare their concatenated versions in different orders. We will sort the numbers based on this comparison, ensuring that the resulting concatenation produces the largest number. The program will then print the largest number formed by the sorted input. Here’s a C program to implement this solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Comparison function to compare two strings based on concatenation
int compare(const void *a, const void *b) {
// Convert the pointers to strings
char *str1 = *(char **)a;
char *str2 = *(char **)b;
// Compare concatenated strings in both orders
if (strcmp(str1, str2) > 0) return -1;
if (strcmp(str1, str2) < 0) return 1;
return 0;
}
int main() {
int n;
// Read the number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Create an array of strings to store the numbers
char *arr[n];
// Read the input numbers as strings
printf("Enter the numbers: \n");
for (int i = 0; i < n; i++) {
arr[i] = (char *)malloc(20 * sizeof(char)); // Allocate memory for each string
scanf("%s", arr[i]);
}
// Sort the array using qsort and the custom comparison function
qsort(arr, n, sizeof(char *), compare);
// Print the largest number formed
printf("The largest number formed is: ");
for (int i = 0; i < n; i++) {
printf("%s", arr[i]);
}
// Free allocated memory
for (int i = 0; i < n; i++) {
free(arr[i]);
}
return 0;
}
Explanation:
- Input: The program first takes the number of elements (n) and then takes n numbers as strings. This is necessary because numbers could have different lengths, and we want to treat them as strings for concatenation.
- Sorting: The program sorts the strings based on how they compare when concatenated in both possible orders. For example, for two numbers “34” and “3”, it compares “343” and “334”. It chooses the order that forms the larger concatenated string.
- Output: After sorting the strings, the program concatenates and prints them to form the largest possible number.
- Memory Management: Memory is dynamically allocated for the strings and freed at the end.
Q3. How do you rotate a matrix by 90 degrees? Write a C program for this.
Sample Answer: To rotate a matrix by 90 degrees clockwise, you can follow these steps:
- Transpose the matrix: Swap the rows and columns of the matrix.
- Reverse the rows: After transposing, reverse each row to get the final rotated matrix.
#include <stdio.h>
#define N 3 // Define the size of the matrix (NxN)
// Function to print the matrix
void printMatrix(int matrix[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
// Function to rotate the matrix by 90 degrees clockwise
void rotateMatrix(int matrix[N][N]) {
// Step 1: Transpose the matrix
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
// Swap matrix[i][j] with matrix[j][i]
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// Step 2: Reverse each row
for (int i = 0; i < N; i++) {
int start = 0, end = N - 1;
while (start < end) {
// Swap elements in the row
int temp = matrix[i][start];
matrix[i][start] = matrix[i][end];
matrix[i][end] = temp;
start++;
end--;
}
}
}
int main() {
// Initialize a matrix
int matrix[N][N] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("Original Matrix:\n");
printMatrix(matrix);
// Rotate the matrix by 90 degrees
rotateMatrix(matrix);
printf("\nMatrix after rotating 90 degrees clockwise:\n");
printMatrix(matrix);
return 0;
}
Also Read: Infosys Interview Questions
Q4. How do you find the missing characters to make a string pangram using a C program?
Sample Answer: To answer the coding questions asked in Infosys interview, you need to check if each letter of the alphabet (from ‘a’ to ‘z’) is present in the string. If any letter is missing, you can add it to a list of missing characters. Here is the code to implement this:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define ALPHABET_SIZE 26
// Function to find missing characters for a pangram
void findMissingCharacters(char str[]) {
// Create an array to keep track of letters present in the string
int present[ALPHABET_SIZE] = {0};
// Iterate over each character in the string
for (int i = 0; str[i] != '\0'; i++) {
// Convert the character to lowercase
char ch = tolower(str[i]);
// If the character is a letter, mark it as present
if (ch >= 'a' && ch <= 'z') {
present[ch - 'a'] = 1;
}
}
// Print the missing characters
printf("Missing characters to make the string a pangram: ");
int foundMissing = 0;
for (int i = 0; i < ALPHABET_SIZE; i++) {
if (present[i] == 0) {
printf("%c ", 'a' + i);
foundMissing = 1;
}
}
// If no missing characters, the string is already a pangram
if (!foundMissing) {
printf("None. The string is already a pangram.");
}
printf("\n");
}
int main() {
char str[1000];
// Read input string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Find missing characters to make the string a pangram
findMissingCharacters(str);
return 0;
}
Q5. How do you find the number of unique numbers in a given string? Write a C program for this.
Sample Answer: To find the number of unique numbers in a given string, you need to extract all the numbers from the string and track which ones have already appeared. This can be done by using a data structure like a set (or an array, but a set is more efficient. This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_NUMBERS 1000 // Define a maximum size for the set of unique numbers
// Function to extract and count unique numbers in the string
int countUniqueNumbers(char str[]) {
int uniqueNumbers[MAX_NUMBERS];
int uniqueCount = 0;
// Initialize all entries in uniqueNumbers to -1 (indicating no number is stored)
for (int i = 0; i < MAX_NUMBERS; i++) {
uniqueNumbers[i] = -1;
}
char currentNum[20]; // Buffer to store current number (string format)
int currentIndex = 0;
// Iterate over the string
for (int i = 0; i <= strlen(str); i++) {
if (isdigit(str[i])) {
// Build the number string
currentNum[currentIndex++] = str[i];
} else {
// If currentNum is not empty and we've reached a non-digit
if (currentIndex > 0) {
currentNum[currentIndex] = '\0'; // Null-terminate the current number
int num = atoi(currentNum); // Convert the string to an integer
// Check if the number is already in the uniqueNumbers array
int isUnique = 1;
for (int j = 0; j < uniqueCount; j++) {
if (uniqueNumbers[j] == num) {
isUnique = 0; // Number is already seen
break;
}
}
// If the number is unique, add it to the uniqueNumbers array
if (isUnique) {
uniqueNumbers[uniqueCount++] = num;
}
// Reset currentNum to start building the next number
currentIndex = 0;
}
}
}
return uniqueCount; // Return the count of unique numbers
}
int main() {
char str[1000];
// Read the input string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Count the unique numbers in the string
int result = countUniqueNumbers(str);
// Output the result
printf("Number of unique numbers: %d\n", result);
return 0;
}
Q6. Write a program for the Subtraction of two Matrices.
Sample Answer: To perform the subtraction of two matrices, you need to subtract the corresponding elements of the two matrices. If both matrices are of the same size, matrix subtraction is straightforward.
#include <stdio.h>
#define MAX_ROWS 10
#define MAX_COLS 10
// Function to subtract two matrices
void subtractMatrices(int matrix1[MAX_ROWS][MAX_COLS], int matrix2[MAX_ROWS][MAX_COLS], int result[MAX_ROWS][MAX_COLS], int rows, int cols) {
// Iterate over each element and subtract corresponding elements
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}
// Function to print a matrix
void printMatrix(int matrix[MAX_ROWS][MAX_COLS], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int matrix1[MAX_ROWS][MAX_COLS], matrix2[MAX_ROWS][MAX_COLS], result[MAX_ROWS][MAX_COLS];
int rows, cols;
// Input the dimensions of the matrices
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
// Input the first matrix
printf("Enter the elements of the first matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix1[i][j]);
}
}
// Input the second matrix
printf("Enter the elements of the second matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix2[i][j]);
}
}
// Perform matrix subtraction
subtractMatrices(matrix1, matrix2, result, rows, cols);
// Output the result
printf("\nResult of matrix subtraction:\n");
printMatrix(result, rows, cols);
return 0;
}
Q7. How do you multiply two matrices and show results through another matrix? Write a C program.
Sample Answer: Matrix multiplication involves multiplying rows of the first matrix with columns of the second matrix, and summing up the products of the corresponding elements. The result of the multiplication will be a new matrix. Here is the code:
#include <stdio.h>
#define MAX_ROWS 10
#define MAX_COLS 10
// Function to multiply two matrices
void multiplyMatrices(int matrix1[MAX_ROWS][MAX_COLS], int matrix2[MAX_ROWS][MAX_COLS], int result[MAX_ROWS][MAX_COLS], int rows1, int cols1, int rows2, int cols2) {
// Initialize the result matrix to 0
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
}
}
// Perform matrix multiplication
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
}
// Function to print a matrix
void printMatrix(int matrix[MAX_ROWS][MAX_COLS], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int matrix1[MAX_ROWS][MAX_COLS], matrix2[MAX_ROWS][MAX_COLS], result[MAX_ROWS][MAX_COLS];
int rows1, cols1, rows2, cols2;
// Input dimensions and elements of the first matrix
printf("Enter the number of rows and columns for the first matrix: ");
scanf("%d %d", &rows1, &cols1);
printf("Enter the elements of the first matrix:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
scanf("%d", &matrix1[i][j]);
}
}
// Input dimensions and elements of the second matrix
printf("Enter the number of rows and columns for the second matrix: ");
scanf("%d %d", &rows2, &cols2);
// Check if multiplication is possible (cols1 of matrix1 must equal rows2 of matrix2)
if (cols1 != rows2) {
printf("Matrix multiplication not possible. The number of columns in the first matrix must be equal to the number of rows in the second matrix.\n");
return 1; // Exit the program
}
printf("Enter the elements of the second matrix:\n");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
scanf("%d", &matrix2[i][j]);
}
}
// Perform matrix multiplication
multiplyMatrices(matrix1, matrix2, result, rows1, cols1, rows2, cols2);
// Output the result
printf("\nResult of matrix multiplication:\n");
printMatrix(result, rows1, cols2);
return 0;
}
Q8. How do you convert decimal numbers to binary numbers? Write a C Program.
Sample Answer: To convert a decimal number to binary, you can repeatedly divide the number by 2 and record the remainder for each division. This method generates the binary digits (bits) in reverse order, so you’ll need to reverse the remainder at the end to get the correct binary representation. Here is the code:
#include <stdio.h>
void decimalToBinary(int n) {
// Array to store binary number
int binary[32];
// Index for binary array
int i = 0;
// If n is 0, the binary representation is 0
if (n == 0) {
printf("0");
return;
}
// Generate binary number
while (n > 0) {
binary[i] = n % 2; // Store remainder in the binary array
n = n / 2; // Divide number by 2
i++;
}
// Print binary number in reverse order
printf("Binary: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
printf("\n");
}
int main() {
int num;
// Input the decimal number
printf("Enter a decimal number: ");
scanf("%d", &num);
// Convert and display the binary equivalent
decimalToBinary(num);
return 0;
}
Q9. Write a program in C++ to swap two arrays quickly.
Sample Answer: To swap two arrays in C++, you can use a temporary array to store one array’s values while copying the other array’s values to the first one. However, to do it quickly without needing extra space (except for a constant amount), you can swap the elements of the arrays in place using a simple loop. Here’s a program that demonstrates how to swap two arrays in C++:
#include <iostream>
using namespace std;
// Function to swap two arrays
void swapArrays(int arr1[], int arr2[], int size) {
for (int i = 0; i < size; i++) {
// Swap elements of arr1 and arr2
int temp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = temp;
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int size;
// Input the size of the arrays
cout << "Enter the size of the arrays: ";
cin >> size;
int arr1[size], arr2[size];
// Input elements for the first array
cout << "Enter elements for the first array: ";
for (int i = 0; i < size; i++) {
cin >> arr1[i];
}
// Input elements for the second array
cout << "Enter elements for the second array: ";
for (int i = 0; i < size; i++) {
cin >> arr2[i];
}
// Display the original arrays
cout << "\nOriginal arrays:" << endl;
cout << "Array 1: ";
printArray(arr1, size);
cout << "Array 2: ";
printArray(arr2, size);
// Swap the arrays
swapArrays(arr1, arr2, size);
// Display the arrays after swapping
cout << "\nArrays after swapping:" << endl;
cout << "Array 1: ";
printArray(arr1, size);
cout << "Array 2: ";
printArray(arr2, size);
return 0;
}
Q10. Write a C++ program to find the area of the incircle of a right-angle triangle.
Sample Answer: To find the area of the incircle of a right-angled triangle, we first need to understand the formula for the radius of the incircle.
Formula to find the radius of the incircle of a right-angled triangle:
For a right-angled triangle with sides aaa, bbb, and hypotenuse ccc, the radius rrr of the incircle can be calculated using the formula:
r=a+b−c2r = \frac{a + b – c}{2}r=2a+b−c
Once we have the radius rrr, the area of the incircle can be found using the formula for the area of a circle:
Area of Incircle=πr2\text{Area of Incircle} = \pi r^2Area of Incircle=πr2
Here is a C++ program to calculate the area of the encircle:
#include <iostream>
#include <cmath> // For using sqrt and M_PI
using namespace std;
// Function to calculate the area of the incircle of a right-angled triangle
double calculateIncircleArea(double a, double b, double c) {
// Calculate the radius of the incircle
double r = (a + b - c) / 2.0;
// Calculate and return the area of the incircle
return M_PI * r * r; // M_PI is a constant for Pi
}
int main() {
double a, b, c;
// Input sides of the right-angled triangle
cout << "Enter the lengths of the two perpendicular sides (a and b): ";
cin >> a >> b;
// Calculate the length of the hypotenuse using the Pythagorean theorem
c = sqrt(a * a + b * b);
// Calculate and display the area of the incircle
double area = calculateIncircleArea(a, b, c);
cout << "The area of the incircle is: " << area << endl;
return 0;
}
Pro Tip: Check out our recommended course on how to ace coding interviews to further enhance your skills and prepare like a pro.
Infosys Coding Interview Questions and Answers For Mid-level Candidates
Preparing for a coding interview at Infosys requires a solid understanding of problem-solving skills and technical expertise. Mid-level candidates are often tested on their ability to handle complex coding scenarios, optimize solutions, and apply industry-standard practices. Below are Infosys coding interview questions and answers for mid-level candidates.
Q11. Write a C++ program that converts the given temperature of Fahrenheit into Celsius.
Sample Answer: In this task, we will write a C++ program that converts a given temperature from Fahrenheit to Celsius. The program will prompt the user to input the temperature in Fahrenheit, and then it will apply the formula for conversion. Celsius = (5/9) * (Fahrenheit – 32). The result will be displayed in Celsius after the conversion. Here is the code to implement this solution:
#include <iostream>
using namespace std;
// Function to convert Fahrenheit to Celsius
double fahrenheitToCelsius(double fahrenheit) {
return (5.0 / 9.0) * (fahrenheit - 32);
}
int main() {
double fahrenheit;
// Input the temperature in Fahrenheit
cout << "Enter temperature in Fahrenheit: ";
cin >> fahrenheit;
// Convert Fahrenheit to Celsius
double celsius = fahrenheitToCelsius(fahrenheit);
// Output the temperature in Celsius
cout << fahrenheit << " Fahrenheit is equal to " << celsius << " Celsius." << endl;
return 0;
}
Also Read: Infosys Java Developer Interview Questions
Q12. Write a Python program to find the sum of all the prime numbers between 1 and N.
Sample Answer: In this task, we will write a Python program that calculates the sum of all prime numbers between 1 and a given number N. The program will first define a function to check whether a number is prime, then iterate through all numbers from 2 to N, summing those that are prime. Finally, the program will output the total sum of the prime numbers in the specified range. Here is the code to implement this solution:
# Function to check if a number is prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
# Function to calculate the sum of all prime numbers between 1 and N
def sum_of_primes(N):
total = 0
for num in range(2, N + 1):
if is_prime(num):
total += num
return total
# Main function
if __name__ == "__main__":
N = int(input("Enter the value of N: "))
result = sum_of_primes(N)
print(f"The sum of all prime numbers between 1 and {N} is: {result}")
Q13. Write a Python program to make the largest number from the digits of the array.
Sample Answer: In this task, we will write a Python program that creates the largest number possible from the digits of an array. The program will first convert the elements of the array into strings. Then, it will sort the array in descending order, using a custom sorting technique to ensure that the concatenation of the numbers produces the largest possible number. Finally, the program will join the sorted digits and print the largest number formed.
Here is the code to implement this solution:
# Function to make the largest number from the digits of the array
def make_largest_number(arr):
# Convert all elements of the array to strings
arr = [str(num) for num in arr]
# Sort the array in descending order based on the string comparison of concatenated numbers
arr.sort(reverse=True, key=lambda x: x*10) # Repeat each string to ensure correct comparison
# Join the sorted array into a single string
largest_number = ''.join(arr)
# Return the result
return largest_number
# Main program
if __name__ == "__main__":
arr = list(map(int, input("Enter the digits separated by space: ").split()))
result = make_largest_number(arr)
print(f"The largest number formed is: {result}")
Q14. Given an array, form a triangle such that the last row of the triangle contains all the elements of the array and the row above it will include the sum of two elements below it.
Sample Answer: In this task, we will write a Python program to form a triangle from an array of numbers. The last row of the triangle will contain all the elements of the array, and each subsequent row above it will consist of the sum of two adjacent elements from the row directly below. The program will generate each upper row iteratively until only one element remains at the top, forming the complete triangle.
Here is the code to implement this solution:
def form_triangle(arr):
# Start with the last row being the input array
triangle = [arr]
# Generate each upper row by summing adjacent elements from the row below
while len(arr) > 1:
arr = [arr[i] + arr[i+1] for i in range(len(arr) - 1)]
triangle.insert(0, arr) # Insert the new row at the beginning
return triangle
# Example usage:
arr = [1, 2, 3, 4, 5]
triangle = form_triangle(arr)
for row in triangle:
print(row)
Q15. Given the coordinates of the endpoints of two rectangles, find whether they overlap each other or not.
Sample Answer: In this task, we will write a Python program to determine whether two rectangles, given by the coordinates of their bottom-left and top-right corners, overlap each other. The program will check the conditions for non-overlapping rectangles: if one rectangle is to the left or right of the other, or if one rectangle is above or below the other. If none of these conditions are met, the rectangles overlap.
Here is the code to implement this solution:
def do_rectangles_overlap(rect1, rect2):
# rect1 and rect2 are tuples (x1, y1, x2, y2) representing bottom-left and top-right corners
x1_1, y1_1, x2_1, y2_1 = rect1
x1_2, y1_2, x2_2, y2_2 = rect2
# Check if one rectangle is to the left or right of the other
if x2_1 <= x1_2 or x2_2 <= x1_1:
return False
# Check if one rectangle is above or below the other
if y2_1 <= y1_2 or y2_2 <= y1_1:
return False
return True
# Example usage:
rect1 = (1, 1, 4, 4) # Bottom-left (1,1), Top-right (4,4)
rect2 = (2, 2, 5, 5) # Bottom-left (2,2), Top-right (5,5)
rect3 = (5, 5, 7, 7) # Bottom-left (5,5), Top-right (7,7)
print(do_rectangles_overlap(rect1, rect2)) # Should return True
print(do_rectangles_overlap(rect1, rect3)) # Should return False
Q16. You are given two strings to find whether we can convert one string to another by rotating in two places.
Sample Answer: In this task, we are given two strings and need to check whether one string can be transformed into another by rotating it in two places. To do this, we will rotate the first string by two places in both directions (left and right) and then check if either of the rotated versions matches the second string. If either of the rotated strings matches, the answer is True, otherwise, it is False.
Here is the code to implement this solution:
def can_rotate_in_two_places(s1, s2):
# Check if lengths are equal
if len(s1) != len(s2):
return False
# Concatenate s1 with itself to cover all possible rotations
doubled_s1 = s1 + s1
# Check if s2 is a substring of the doubled string
for i in range(1, len(s1)):
# start from index 1 to ensure we check rotations in two places
if doubled_s1[i:i + len(s2)] == s2:
return True
return False
# Example Usage
s1 = "abcde"
s2 = "deabc"
print(can_rotate_in_two_places(s1, s2)) # Output: True
Q17. Given a list of integers, find the longest subsequence where the difference between every pair of consecutive elements is the same.
Sample Answer: In this task, we need to find the longest subsequence in a list of integers where the difference between every pair of consecutive elements is the same. We will iterate through the list, keeping track of the longest subsequence where the difference remains constant. If the difference changes, we will reset the subsequence and start a new one. The program will then return the longest subsequence found.
Here is the code to implement this solution:
def longest_arithmetic_subsequence(arr):
if len(arr) <= 1:
return arr
# Variables to keep track of the current subsequence and the longest subsequence
max_length = 1
current_subsequence = [arr[0]]
longest_subsequence = [arr[0]]
diff = None
for i in range(1, len(arr)):
# If the difference is the same as the previous one, continue the subsequence
if diff is None or arr[i] - arr[i-1] == diff:
current_subsequence.append(arr[i])
else:
# Otherwise, reset the subsequence
if len(current_subsequence) > max_length:
max_length = len(current_subsequence)
longest_subsequence = current_subsequence
current_subsequence = [arr[i-1], arr[i]]
# Update the difference
diff = arr[i] - arr[i-1]
# Check the last subsequence
if len(current_subsequence) > max_length:
longest_subsequence = current_subsequence
return longest_subsequence
# Example usage
arr = [1, 7, 10, 13, 14, 19, 20]
result = longest_arithmetic_subsequence(arr)
print(f"The longest arithmetic subsequence is: {result}")
Q18. Write a C++ program to swap two numbers.
Sample Answer: This task requires us to write a program that swaps two numbers. The program will prompt the user to input two numbers and then swap them using a temporary variable. The result will be displayed before and after the swap.
Here is the code to implement this solution:
#include <iostream>
using namespace std;
int main() {
// Declare two variables to store the numbers
int a, b;
// Input the values of the numbers
cout << "Enter the first number: ";
cin >> a;
cout << "Enter the second number: ";
cin >> b;
// Display the values before swapping
cout << "Before swapping:" << endl;
cout << "a = " << a << ", b = " << b << endl;
// Swap the values of a and b using a temporary variable
int temp = a;
a = b;
b = temp;
// Display the values after swapping
cout << "After swapping:" << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Q19. Write a program to convert the decimal number to the octal number. (C++)
Sample Answer: In this task, we will write a program to convert a decimal number to its octal equivalent. The program will repeatedly divide the decimal number by 8 and store the remainders to form the octal number. After the conversion, the program will display the octal result.
Here is the code to implement this solution:
#include <iostream>
using namespace std;
int main() {
int decimalNumber, remainder;
string octalNumber = "";
// Input decimal number
cout << "Enter a decimal number: ";
cin >> decimalNumber;
// Convert decimal to octal
while (decimalNumber != 0) {
remainder = decimalNumber % 8; // Get remainder when divided by 8
octalNumber = to_string(remainder) + octalNumber; // Prepend the remainder
decimalNumber /= 8; // Update decimal number by dividing by 8
}
// Output the octal number
cout << "The octal equivalent is: " << octalNumber << endl;
return 0;
}
Q20. Write a Python program to convert a decimal number to a hexadecimal number.
Sample Answer: This task involves converting a decimal number to its hexadecimal equivalent. We will use Python’s built-in hex() function to perform the conversion. The program will input a decimal number from the user and output the corresponding hexadecimal number after stripping the 0x prefix.
Here is the code to implement this solution:
def decimal_to_hexadecimal(decimal_number):
# Using built-in hex function to convert decimal to hexadecimal
hexadecimal_number = hex(decimal_number)
return hexadecimal_number[2:] # Removing the '0x' prefix
# Input from user
decimal_number = int(input("Enter a decimal number: "))
# Convert to hexadecimal
hexadecimal_number = decimal_to_hexadecimal(decimal_number)
# Output the result
print(f"The hexadecimal equivalent of {decimal_number} is: {hexadecimal_number}")
Infosys Coding Interview Questions And Answers For Experienced Candidates
Preparing for a coding interview with Infosys as an experienced professional requires a strategic approach to problem-solving and technical expertise. Below are Infosys coding interview questions and answers for experienced candidates.
Q21. Write a Python program to swap two numbers without using a third variable.
Sample Answer: In this task, we need to write a Python program to swap two numbers without using a third variable. The program will take two numbers as input, display their values before swapping, and then swap them using arithmetic operations. The swapped values will be displayed at the end.
Here is the code to implement this solution:
# Take input from the user
x = float(input("Enter the first number: "))
y = float(input("Enter the second number: "))
# Display the original values
print(f"Before swapping: x = {x}, y = {y}")
# Swapping the values using arithmetic operations
x = x + y
y = x - y
x = x - y
# Display the swapped values
print(f"After swapping: x = {x}, y = {y}")
Q22. Write a Python program to convert an octal number to a binary number.
Sample Answer: This task requires converting an octal number to its binary equivalent. The program will first convert the octal number to decimal and then convert the decimal number to binary. The result will be displayed as the binary equivalent of the given octal number.
Here is the code to implement this solution:
def octal_to_binary(octal):
# Convert octal to decimal
decimal = int(octal, 8)
# Convert decimal to binary
binary = bin(decimal).replace("0b", "")
return binary
# Input octal number from the user
octal_number = input("Enter an octal number: ")
# Call the function and display the result
binary_number = octal_to_binary(octal_number)
print(f"The binary equivalent of octal {octal_number} is {binary_number}")
Also Read: Infosys BPM Interview Questions
Q23. Write a Java program to convert an octal number to a decimal number.
Sample Answer: In this task, we are given an octal number, and we need to write a Java program to convert it into its decimal equivalent. The program will use Java’s Integer.parseInt() method to convert the octal string to a decimal integer and then output the result.
Here is the code to implement this solution:
import java.util.Scanner;
public class OctalToDecimal {
public static void main(String[] args) {
// Create a scanner object to read input
Scanner scanner = new Scanner(System.in);
// Ask the user for an octal number
System.out.print("Enter an octal number: ");
String octal = scanner.nextLine();
// Convert the octal string to a decimal integer using parseInt method
try {
int decimal = Integer.parseInt(octal, 8); // The second parameter (8) denotes the base (octal)
System.out.println("The decimal equivalent is: " + decimal);
} catch (NumberFormatException e) {
System.out.println("Invalid octal number entered.");
}
// Close the scanner
scanner.close();
}
}
Q24. Write a Java program to find the spiral traversal of a matrix.
Sample Answer: The task is to traverse a matrix in a spiral order, starting from the top-left corner and moving right, down, left, and up repeatedly until all elements are traversed. The Java program will implement this traversal and print the elements in the correct spiral order.
Here is the code to implement this solution:
import java.util.*;
public class SpiralTraversal {
// Function to print the spiral traversal of a matrix
public static void spiralTraversal(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return;
}
// Define boundaries
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
// List to store the spiral order
List<Integer> result = new ArrayList<>();
// Traverse the matrix in a spiral order
while (top <= bottom && left <= right) {
// Traverse from left to right along the top row
for (int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
top++; // Move the top boundary down
// Traverse from top to bottom along the right column
for (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--; // Move the right boundary left
if (top <= bottom) {
// Traverse from right to left along the bottom row
for (int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
}
bottom--; // Move the bottom boundary up
}
if (left <= right) {
// Traverse from bottom to top along the left column
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++; // Move the left boundary right
}
}
// Print the result
for (int num : result) {
System.out.print(num + " ");
}
}
// Main method to test the spiral traversal
public static void main(String[] args) {
// Sample matrix for testing
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Call the function to print spiral traversal
spiralTraversal(matrix);
}
}
Q25. Write a Java code to print the first N Fibonacci numbers.
Sample Answer: In this task, we need to write a Java program to print the first N Fibonacci numbers. The program will take an input N and print the Fibonacci sequence up to that N-th number by using a loop and updating two variables to generate the sequence.
Here is the code to implement this solution:
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user to input N
System.out.print("Enter the number of Fibonacci numbers to print: ");
int N = scanner.nextInt();
// First two Fibonacci numbers
int first = 0, second = 1;
System.out.println("The first " + N + " Fibonacci numbers are:");
// Print the first N Fibonacci numbers
for (int i = 0; i < N; i++) {
if (i == 0) {
System.out.print(first + " ");
continue;
}
if (i == 1) {
System.out.print(second + " ");
continue;
}
// Calculate the next Fibonacci number
int next = first + second;
System.out.print(next + " ");
// Update the values of first and second
first = second;
second = next;
}
scanner.close();
}
}
Also Read: How to get Job at Infosys?
Q26. Write a Java code to find the first non-repeating character from a stream of characters.
Sample Answer: This task asks us to find the first non-repeating character from a stream of characters in a Java program. The program will use a map to track the frequency of each character and then identify the first character with a count of 1 as the first non-repeating character.
Here is the code to implement this solution:
import java.util.*;
public class FirstNonRepeatingCharacter {
public static void main(String[] args) {
// Test the function with an example
String stream = "aabccdbd";
System.out.println("First non-repeating character: " + firstNonRepeating(stream));
}
public static char firstNonRepeating(String stream) {
// Map to store frequency of each character
Map<Character, Integer> charCount = new LinkedHashMap<>();
// Iterate over the stream
for (char ch : stream.toCharArray()) {
// Update the frequency count for each character
charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);
}
// Iterate over the map to find the first non-repeating character
for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
// If no non-repeating character exists
return '\0'; // Return null character if no unique character is found
}
}
Q27. Write a Java code to remove duplicates from a sorted array.
Sample Answer: The task requires writing a Java program to remove duplicates from a sorted array. The program will traverse through the sorted array, comparing consecutive elements, and shift unique elements to the front of the array. It will then return the new length of the array after removing duplicates.
Here is the code to implement this solution:
public class RemoveDuplicates {
public static int removeDuplicates(int[] nums) {
// Check if the array is empty or contains only one element
if (nums == null || nums.length == 0) {
return 0;
}
int uniqueIndex = 1; // Start from the second element
// Traverse through the sorted array
for (int i = 1; i < nums.length; i++) {
// If current element is not equal to previous element, add it to the unique position
if (nums[i] != nums[i - 1]) {
nums[uniqueIndex] = nums[i];
uniqueIndex++;
}
}
// Return the new length of the array without duplicates
return uniqueIndex;
}
public static void main(String[] args) {
int[] nums = {1, 1, 2, 2, 3, 3, 4}; // Example sorted array
int length = removeDuplicates(nums);
// Print the array after removing duplicates
System.out.println("Array after removing duplicates:");
for (int i = 0; i < length; i++) {
System.out.print(nums[i] + " ");
}
System.out.println();
System.out.println("New length: " + length);
}
}
Q28. What is the difference between C++ and Java?
Sample Answer: C++ and Java are both powerful programming languages, but they have different design and use cases. Here is a table illustrating the key differences between C++ and Java:
Features | C++ | Java |
Primary Use | Originally designed for systems and application programming | Developed primarily for use in printing systems and supports network computing |
Platform Dependency | C++ is platform-dependent, tailored for specific operating systems or hardware configurations | Java is platform-independent, runs on any device or OS with a compatible Java Virtual Machine (JVM) |
Target Applications | Provides powerful tools for managing hardware resources and creating efficient applications | Ideal for developing distributed applications |
Accessibility | More complex due to platform-specific considerations | More accessible for beginners, abstracts away platform-specific complexities |
Q29. Define class and object in C++.
Sample Answer: In C++, a class is a user-defined data type that serves as a blueprint for creating objects. It combines both data and the functions that operate on that data. The variables that store the data within the class are referred to as data members, while the functions that operate on or manipulate these data members are known as member functions.
An object is an instance of a class. Each object represents a specific realization or instantiation of the class, and it can be viewed as a unique example of the class.
Q30. Explain some important differences between C and C++
Sample Answer: C and C++ are both powerful programming languages, but they differ significantly in terms of features, design philosophy, and usage.
Aspect | C | C++ |
Paradigm | C is a procedural language, focused on functions and structured programming. It emphasizes the use of procedures (functions) to operate on data, with a strong focus on step-by-step execution. | C++, on the other hand, is a multi-paradigm language that supports both procedural and object-oriented programming (OOP). It allows for the creation of classes, objects, and methods, making it more suited for complex systems. |
Object-Oriented Features: | C lacks native support for classes, objects, inheritance, polymorphism, and encapsulation, which are central concepts in object-oriented programming. | C++ incorporates these features, enabling more modular and reusable code. The ability to use classes and objects enhances code organization and maintenance. |
Memory Management: | C provides manual memory management using functions like malloc() and free(). | C++ introduces the concept of constructors and destructors for automatic memory management and the new and delete operators to allocate and deallocate memory dynamically. |
Standard Libraries: | C has a smaller standard library, primarily focusing on basic functionalities like input/output, memory management, and string manipulation. | C++ offers a richer standard library, including the Standard Template Library (STL), which provides data structures like vectors, lists, and algorithms for efficient programming. |


Conclusion
Preparing for Infosys coding questions requires a blend of strong problem-solving skills, an understanding of algorithms, and consistent practice. By focusing on key concepts such as data structures, time complexity, and coding patterns, candidates can enhance their chances of success. Regularly practising on coding platforms and developing a systematic approach will ensure you’re well-prepared to confidently tackle Infosys’s coding interviews. If you are interested in C++ coding jobs, check our blog on the C++ coding interview questions to ace your interview.
FAQs
Answer: Infosys rarely repeats coding questions from previous years. However, the concepts and difficulty level of the questions tend to be similar in subsequent exams.
Answer: Yes, Python is employed at Infosys, particularly in roles related to software development, automation, and data analysis. It is a widely used language for various projects within the organization.
Answer: Yes, Infosys places a strong emphasis on DSA during its interview process. Candidates are frequently evaluated on their knowledge of data structures, algorithms, and problem-solving skills.