Table of Contents
Infosys Coding Questions
Infosys, a global leader in next-generation digital services and consulting, is known for its rigorous coding assessments during recruitment. These coding questions evaluate a candidate’s problem-solving abilities, logical thinking, and proficiency in programming languages. The questions range from simple data structure and algorithm problems to more complex ones involving real-world scenarios. This blog focuses on the Top 13 Infosys Coding Questions and Answers for the examination.
Infosys coding questions often test a candidate’s understanding of concepts like arrays, strings, linked lists, trees, recursion, and dynamic programming. Solving these questions efficiently and effectively is crucial for aspiring candidates to showcase their coding skills and stand out in the competitive hiring process.
Attempt Free Infosys Mock Test 2024
13 Infosys Coding Questions and Answers 2024
In Infosys Exam, they have 3 Infosys coding questions, to be completed in 3 hours. So, candidates should practice the Infosys coding questions and answers for the Infosys Exam.
Infosys Coding Questions | Infosys Coding Topics | Difficulty Level |
1 | Aptitude, Algorithm and Data Structures. | Easy |
2 | Greedy Algorithm | Medium |
3 | Dynamic Programming | Hard Level |
Applicants of the Infosys examination can refer to the coding questions and answers added here. Check the Infosys coding questions and answers, and improve your coding skills.
1. Write a program to arrange the given number to form the biggest number.
Ans.
Python
from functools import cmp_to_keydef compare(x, y): # Compare combined numbers to determine order if x + y > y + x: return -1 elif x + y < y + x: return 1 else: return 0def largest_number(nums): # Convert numbers to strings for easy concatenation str_nums = [str(num) for num in nums] # Sort numbers using custom comparator str_nums.sort(key=cmp_to_key(compare)) # Join sorted numbers to form the largest number largest_num = ''.join(str_nums) # Edge case for leading zeros return largest_num if largest_num[0] != '0' else '0'# Example usagenumbers = [3, 30, 34, 5, 9]print("The largest number is:", largest_number(numbers))
Output
The largest number is: 9534330
Java
import java.util.Arrays;import java.util.Comparator;public class LargestNumber { // Custom comparator to decide the order based on concatenation private static class NumberComparator implements Comparator<String> { @Override public int compare(String x, String y) { String order1 = x + y; String order2 = y + x; return order2.compareTo(order1); // reverse order for descending } } public static String largestNumber(int[] nums) { // Convert int array to String array String[] strNums = Arrays.stream(nums) .mapToObj(String::valueOf) .toArray(String[]::new); // Sort array using custom comparator Arrays.sort(strNums, new NumberComparator()); // Edge case: Check if the largest number is 0 if (strNums[0].equals("0")) { return "0"; } // Join sorted array to form the largest number StringBuilder largestNum = new StringBuilder(); for (String num : strNums) { largestNum.append(num); } return largestNum.toString(); } public static void main(String[] args) { int[] numbers = {3, 30, 34, 5, 9}; System.out.println("The largest number is: " + largestNumber(numbers)); }}
Output
The largest number is: 9534330
.NET
using System;using System.Linq;public class LargestNumber{ // Custom comparator to decide the order based on concatenation public class NumberComparer : IComparer<string> { public int Compare(string x, string y) { string order1 = x + y; string order2 = y + x; return order2.CompareTo(order1); // reverse order for descending } } public static string LargestNumberFromArray(int[] nums) { // Convert int array to string array var strNums = nums.Select(num => num.ToString()).ToArray(); // Sort array using custom comparator Array.Sort(strNums, new NumberComparer()); // Edge case: Check if the largest number is 0 if (strNums[0] == "0") { return "0"; } // Join sorted array to form the largest number return string.Join("", strNums); } public static void Main(string[] args) { int[] numbers = { 3, 30, 34, 5, 9 }; Console.WriteLine("The largest number is: " + LargestNumberFromArray(numbers)); }}
Output
The largest number is: 9534330
2. Find the next permutation of the given string in the Program
Ans.
Python
def next_permutation(s): # Convert string to list for mutability arr = list(s) n = len(arr) # Step 1: Find the largest index i such that arr[i-1] < arr[i] i = n - 1 while i > 0 and arr[i - 1] >= arr[i]: i -= 1 # If no such index exists, the permutation is the last permutation if i == 0: return ''.join(sorted(arr)) # Step 2: Find the largest index j such that arr[j] > arr[i-1] j = n - 1 while arr[j] <= arr[i - 1]: j -= 1 # Step 3: Swap arr[i-1] with arr[j] arr[i - 1], arr[j] = arr[j], arr[i - 1] # Step 4: Reverse the suffix starting from index i arr[i:] = arr[n - 1:i - 1:-1] return ''.join(arr)# Example usages = "123"print("Next permutation of", s, ":", next_permutation(s))
Output
Next permutation is: 536479
Java
import java.util.Arrays;public class NextPermutation { public static String nextPermutation(String s) { char[] arr = s.toCharArray(); int n = arr.length; // Step 1: Find the largest index i such that arr[i-1] < arr[i] int i = n - 1; while (i > 0 && arr[i - 1] >= arr[i]) { i--; } // If no such index exists, the permutation is the last permutation if (i == 0) { Arrays.sort(arr); return new String(arr); } // Step 2: Find the largest index j such that arr[j] > arr[i-1] int j = n - 1; while (arr[j] <= arr[i - 1]) { j--; } // Step 3: Swap arr[i-1] with arr[j] char temp = arr[i - 1]; arr[i - 1] = arr[j]; arr[j] = temp; // Step 4: Reverse the sequence from arr[i] to arr[n-1] reverse(arr, i, n - 1); return new String(arr); } private static void reverse(char[] arr, int start, int end) { while (start < end) { char temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } public static void main(String[] args) { String s = "534976"; System.out.println("Next permutation is: " + nextPermutation(s)); }}
Output
Next permutation is: 536479
.NET
using System;public class NextPermutation{ public static string GetNextPermutation(string s) { char[] arr = s.ToCharArray(); int n = arr.Length; // Step 1: Find the largest index i such that arr[i-1] < arr[i] int i = n - 1; while (i > 0 && arr[i - 1] >= arr[i]) { i--; } // If no such index exists, the permutation is the last permutation if (i == 0) { Array.Sort(arr); return new string(arr); } // Step 2: Find the largest index j such that arr[j] > arr[i-1] int j = n - 1; while (arr[j] <= arr[i - 1]) { j--; } // Step 3: Swap arr[i-1] with arr[j] char temp = arr[i - 1]; arr[i - 1] = arr[j]; arr[j] = temp; // Step 4: Reverse the sequence from arr[i] to arr[n-1] Array.Reverse(arr, i, n - i); return new string(arr); } public static void Main(string[] args) { string s = "534976"; Console.WriteLine("Next permutation is: " + GetNextPermutation(s)); }}
Output
Next permutation is: 536479
3. How do you rotate a matrix by 90 degrees? Write a program for this.
Ans.
Python
def rotate_matrix(matrix): n = len(matrix) # Transpose the matrix for i in range(n): for j in range(i, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Reverse each row for i in range(n): matrix[i].reverse()# Example usagematrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]rotate_matrix(matrix)print("Rotated matrix:")for row in matrix: print(row)
Output
Rotated matrix:[7, 4, 1][8, 5, 2][9, 6, 3]
Java
public class RotateMatrix { public static void rotate(int[][] matrix) { int n = matrix.length; // Transpose the matrix for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } // Reverse each row for (int i = 0; i < n; i++) { int left = 0; int right = n - 1; while (left < right) { int temp = matrix[i][left]; matrix[i][left] = matrix[i][right]; matrix[i][right] = temp; left++; right--; } } } public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; rotate(matrix); System.out.println("Rotated matrix:"); for (int[] row : matrix) { for (int num : row) { System.out.print(num + " "); } System.out.println(); } }}
Output
Rotated matrix:[7, 4, 1][8, 5, 2][9, 6, 3]
.NET
using System;public class RotateMatrix{ public static void Rotate(int[][] matrix) { int n = matrix.Length; // Transpose the matrix for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } // Reverse each row for (int i = 0; i < n; i++) { Array.Reverse(matrix[i]); } } public static void Main(string[] args) { int[][] matrix = new int[][] { new int[] {1, 2, 3}, new int[] {4, 5, 6}, new int[] {7, 8, 9} }; Rotate(matrix); Console.WriteLine("Rotated matrix:"); foreach (var row in matrix) { Console.WriteLine(string.Join(", ", row)); } }}
Output
Rotated matrix:7, 4, 18, 5, 29, 6, 3
4. How do you find the missing characters to make a string pangram? Write a program.
Ans.
Python
def find_missing_characters(s): alphabet = set('abcdefghijklmnopqrstuvwxyz') s = s.lower() present_chars = set(s) missing_chars = alphabet - present_chars return ''.join(sorted(missing_chars))# Example usageinput_string = "The quick brown fox jumps over a lazy dog"missing_chars = find_missing_characters(input_string)print(f"Missing characters to make the string a pangram: '{missing_chars}'")
Output
Missing characters to make the string a pangram: ''
Java
import java.util.HashSet;import java.util.Set;public class PangramChecker { public static String findMissingCharacters(String s) { Set<Character> alphabet = new HashSet<>(); for (char c = 'a'; c <= 'z'; c++) { alphabet.add(c); } s = s.toLowerCase(); Set<Character> presentChars = new HashSet<>(); for (char c : s.toCharArray()) { if (Character.isLetter(c)) { presentChars.add(c); } } alphabet.removeAll(presentChars); StringBuilder missingChars = new StringBuilder(); for (char c : alphabet) { missingChars.append(c); } return missingChars.toString(); } public static void main(String[] args) { String inputString = "The quick brown fox jumps over a lazy dog"; String missingChars = findMissingCharacters(inputString); System.out.println("Missing characters to make the string a pangram: '" + missingChars + "'"); // For a non-pangram example inputString = "Hello World"; missingChars = findMissingCharacters(inputString); System.out.println("Missing characters to make the string a pangram: '" + missingChars + "'"); }}
Output
Missing characters to make the string a pangram: ''Missing characters to make the string a pangram: 'abcfijkmnpqstuvxyz'
.NET
using System;using System.Collections.Generic;public class PangramChecker{ public static string FindMissingCharacters(string s) { HashSet<char> alphabet = new HashSet<char>("abcdefghijklmnopqrstuvwxyz"); s = s.ToLower(); HashSet<char> presentChars = new HashSet<char>(); foreach (char c in s) { if (char.IsLetter(c)) { presentChars.Add(c); } } alphabet.ExceptWith(presentChars); List<char> missingChars = new List<char>(alphabet); missingChars.Sort(); return new string(missingChars.ToArray()); } public static void Main(string[] args) { string inputString = "The quick brown fox jumps over a lazy dog"; string missingChars = FindMissingCharacters(inputString); Console.WriteLine("Missing characters to make the string a pangram: '" + missingChars + "'"); // For a non-pangram example inputString = "Hello World"; missingChars = FindMissingCharacters(inputString); Console.WriteLine("Missing characters to make the string a pangram: '" + missingChars + "'"); }}
Output
Missing characters to make the string a pangram: ''Missing characters to make the string a pangram: 'abcfijkmnpqstuvxyz'
5. How do you find the number of unique numbers in a given string? Write a program.
Ans.
Python
import redef count_unique_numbers(s): # Find all numbers in the string using regex numbers = re.findall(r'\d+', s) # Convert to integers to handle leading zeros and find unique numbers unique_numbers = set(int(num) for num in numbers) return len(unique_numbers)# Example usageinput_string = "abc123def456abc123def7890123"unique_count = count_unique_numbers(input_string)print(f"Number of unique numbers in the string: {unique_count}")
Output
Number of unique numbers in the string: 3
Java
import java.util.HashSet;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;public class UniqueNumbers { public static int countUniqueNumbers(String s) { // Create a pattern to find all numbers Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(s); // Use a set to store unique numbers Set<Integer> uniqueNumbers = new HashSet<>(); // Find all matches and add to the set as integers while (matcher.find()) { uniqueNumbers.add(Integer.parseInt(matcher.group())); } return uniqueNumbers.size(); } public static void main(String[] args) { String inputString = "abc123def456abc123def7890123"; int uniqueCount = countUniqueNumbers(inputString); System.out.println("Number of unique numbers in the string: " + uniqueCount); }}
Output
Number of unique numbers in the string: 3
.NET
using System;using System.Collections.Generic;using System.Text.RegularExpressions;public class UniqueNumbers{ public static int CountUniqueNumbers(string s) { // Create a pattern to find all numbers Regex regex = new Regex(@"\d+"); MatchCollection matches = regex.Matches(s); // Use a set to store unique numbers HashSet<int> uniqueNumbers = new HashSet<int>(); // Find all matches and add to the set as integers foreach (Match match in matches) { uniqueNumbers.Add(int.Parse(match.Value)); } return uniqueNumbers.Count; } public static void Main(string[] args) { string inputString = "abc123def456abc123def7890123"; int uniqueCount = CountUniqueNumbers(inputString); Console.WriteLine("Number of unique numbers in the string: " + uniqueCount); }}
6. Write a program for the Subtraction of two Matrices.
Ans.
Python
def subtract_matrices(matrix1, matrix2): if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]): raise ValueError("Matrices must have the same dimensions for subtraction") result = [] for i in range(len(matrix1)): row = [] for j in range(len(matrix1[0])): row.append(matrix1[i][j] - matrix2[i][j]) result.append(row) return result# Example usagematrix1 = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]matrix2 = [ [9, 8, 7], [6, 5, 4], [3, 2, 1]]result = subtract_matrices(matrix1, matrix2)print("Result of subtraction:")for row in result: print(row)
Output
Result of subtraction:[-8, -6, -4][-2, 0, 2][4, 6, 8]
Java
public class MatrixSubtraction { public static int[][] subtractMatrices(int[][] matrix1, int[][] matrix2) { if (matrix1.length != matrix2.length || matrix1[0].length != matrix2[0].length) { throw new IllegalArgumentException("Matrices must have the same dimensions for subtraction"); } int[][] result = new int[matrix1.length][matrix1[0].length]; for (int i = 0; i < matrix1.length; i++) { for (int j = 0; j < matrix1[0].length; j++) { result[i][j] = matrix1[i][j] - matrix2[i][j]; } } return result; } public static void main(String[] args) { int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[][] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; int[][] result = subtractMatrices(matrix1, matrix2); System.out.println("Result of subtraction:"); for (int[] row : result) { for (int num : row) { System.out.print(num + " "); } System.out.println(); } }}
Output
Result of subtraction:-8 -6 -4 -2 0 2 4 6 8
.NET
using System;public class MatrixSubtraction{ public static int[,] SubtractMatrices(int[,] matrix1, int[,] matrix2) { if (matrix1.GetLength(0) != matrix2.GetLength(0) || matrix1.GetLength(1) != matrix2.GetLength(1)) { throw new ArgumentException("Matrices must have the same dimensions for subtraction"); } int rows = matrix1.GetLength(0); int cols = matrix1.GetLength(1); int[,] result = new int[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result[i, j] = matrix1[i, j] - matrix2[i, j]; } } return result; } public static void Main(string[] args) { int[,] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[,] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; int[,] result = SubtractMatrices(matrix1, matrix2); Console.WriteLine("Result of subtraction:"); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { Console.Write(result[i, j] + " "); } Console.WriteLine(); } }}
Output
Result of subtraction:-8 -6 -4-2 0 24 6 8
7. How do you multiply two matrices and show results through another matrix? Write a program.
Ans.
Python
def multiply_matrices(matrix1, matrix2): if len(matrix1[0]) != len(matrix2): raise ValueError("Number of columns in first matrix must be equal to number of rows in second matrix") result = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))] for i in range(len(matrix1)): for j in range(len(matrix2[0])): for k in range(len(matrix2)): result[i][j] += matrix1[i][k] * matrix2[k][j] return result# Example usagematrix1 = [ [1, 2, 3], [4, 5, 6],]matrix2 = [ [7, 8], [9, 10], [11, 12]]result = multiply_matrices(matrix1, matrix2)print("Result of matrix multiplication:")for row in result: print(row)
Output
Result of matrix multiplication:[58, 64][139, 154]
Java
public class MatrixMultiplication { public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) { if (matrix1[0].length != matrix2.length) { throw new IllegalArgumentException("Number of columns in first matrix must be equal to number of rows in second matrix"); } int[][] result = new int[matrix1.length][matrix2[0].length]; for (int i = 0; i < matrix1.length; i++) { for (int j = 0; j < matrix2[0].length; j++) { for (int k = 0; k < matrix2.length; k++) { result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } return result; } public static void main(String[] args) { int[][] matrix1 = { {1, 2, 3}, {4, 5, 6} }; int[][] matrix2 = { {7, 8}, {9, 10}, {11, 12} }; int[][] result = multiplyMatrices(matrix1, matrix2); System.out.println("Result of matrix multiplication:"); for (int[] row : result) { for (int num : row) { System.out.print(num + " "); } System.out.println(); } }}
Output
Result of matrix multiplication:58 64 139 154
.NET
using System;public class MatrixMultiplication{ public static int[,] MultiplyMatrices(int[,] matrix1, int[,] matrix2) { if (matrix1.GetLength(1) != matrix2.GetLength(0)) { throw new ArgumentException("Number of columns in first matrix must be equal to number of rows in second matrix"); } int[,] result = new int[matrix1.GetLength(0), matrix2.GetLength(1)]; for (int i = 0; i < matrix1.GetLength(0); i++) { for (int j = 0; j < matrix2.GetLength(1); j++) { for (int k = 0; k < matrix2.GetLength(0); k++) { result[i, j] += matrix1[i, k] * matrix2[k, j]; } } } return result; } public static void Main(string[] args) { int[,] matrix1 = { {1, 2, 3}, {4, 5, 6} }; int[,] matrix2 = { {7, 8}, {9, 10}, {11, 12} }; int[,] result = MultiplyMatrices(matrix1, matrix2); Console.WriteLine("Result of matrix multiplication:"); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { Console.Write(result[i, j] + " "); } Console.WriteLine(); } }}
Output
Result of matrix multiplication:58 64 139 154
8. How do you convert decimal numbers to binary numbers? Write a Program.
Ans.
Python
def decimal_to_binary(n): return bin(n)[2:]# Example usagedecimal_number = 10binary_number = decimal_to_binary(decimal_number)print(f"The binary representation of {decimal_number} is: {binary_number}")
Output
The binary representation of 10 is: 1010
Java
public class DecimalToBinary { public static String decimalToBinary(int n) { return Integer.toBinaryString(n); } public static void main(String[] args) { int decimalNumber = 10; String binaryNumber = decimalToBinary(decimalNumber); System.out.println("The binary representation of " + decimalNumber + " is: " + binaryNumber); }}
Output
The binary representation of 10 is: 1010
.NET
using System;public class DecimalToBinary{ public static string DecimalToBinaryString(int n) { return Convert.ToString(n, 2); } public static void Main(string[] args) { int decimalNumber = 10; string binaryNumber = DecimalToBinaryString(decimalNumber); Console.WriteLine("The binary representation of " + decimalNumber + " is: " + binaryNumber); }}
Output
The binary representation of 10 is: 1010
9. Write a program in C++ to swap two arrays quickly.
Ans. Python
# Define arraysarray1 = [1, 2, 3]array2 = [4, 5, 6]# Before swappingprint("Before swapping:")print("Array 1:", array1)print("Array 2:", array2)# Swap arraystemp = array1array1 = array2array2 = temp# After swappingprint("\nAfter swapping:")print("Array 1:", array1)print("Array 2:", array2)
Output
Before swapping:Array 1: [1, 2, 3]Array 2: [4, 5, 6]After swapping:Array 1: [4, 5, 6]Array 2: [1, 2, 3]
Java
public class ArraySwap { public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; System.out.println("Before swapping:"); System.out.println("Array 1: " + java.util.Arrays.toString(array1)); System.out.println("Array 2: " + java.util.Arrays.toString(array2)); // Swap arrays int[] temp = array1; array1 = array2; array2 = temp; System.out.println("\nAfter swapping:"); System.out.println("Array 1: " + java.util.Arrays.toString(array1)); System.out.println("Array 2: " + java.util.Arrays.toString(array2)); }}
.NET
using System;class ArraySwap { static void Main(string[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; Console.WriteLine("Before swapping:"); Console.WriteLine("Array 1: " + string.Join(", ", array1)); Console.WriteLine("Array 2: " + string.Join(", ", array2)); // Swap arrays int[] temp = array1; array1 = array2; array2 = temp; Console.WriteLine("\nAfter swapping:"); Console.WriteLine("Array 1: " + string.Join(", ", array1)); Console.WriteLine("Array 2: " + string.Join(", ", array2)); }}
10. Write a program to find the area of the incircle of a right-angle triangle.
Ans.
Python
import math# Sample input valuesa = 3b = 4c = 5# Calculate semiperimeters = (a + b + c) / 2# Calculate area using Heron's formulaarea_triangle = math.sqrt(s * (s - a) * (s - b) * (s - c))# Calculate radius of incircleradius = area_triangle / s# Calculate area of incirclearea_incircle = math.pi * radius**2print("Area of the incircle of the right-angle triangle:", area_incircle)
Output
Area of the incircle of the right-angle triangle: 3.141592653589793
Java
import java.util.Scanner;public class IncircleArea { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the lengths of the sides of the right-angle triangle:"); System.out.print("Length of side a: "); double a = scanner.nextDouble(); System.out.print("Length of side b: "); double b = scanner.nextDouble(); System.out.print("Length of side c: "); double c = scanner.nextDouble(); double perimeter = a + b + c; double area = perimeter / 2; System.out.println("Area of the incircle of the right-angle triangle: " + area); }}
Output
Enter the lengths of the sides of the right-angle triangle
.NET
using System;class IncircleArea{ static void Main(string[] args) { Console.Write("Enter the length of side a: "); double a = double.Parse(Console.ReadLine()); Console.Write("Enter the length of side b: "); double b = double.Parse(Console.ReadLine()); Console.Write("Enter the length of side c: "); double c = double.Parse(Console.ReadLine()); double perimeter = a + b + c; double area = perimeter / 2; Console.WriteLine("Area of the incircle of the right-angle triangle: " + area); }}
11. Write a program that converts the given temperature of Fahrenheit into Celsius.
Ans.
Python
def fahrenheit_to_celsius(fahrenheit): return (fahrenheit - 32) * 5 / 9# Example usagefahrenheit = float(input("Enter temperature in Fahrenheit: "))celsius = fahrenheit_to_celsius(fahrenheit)print("Temperature in Celsius:", celsius)
Output
Enter temperature in Fahrenheit: 98.6Temperature in Celsius: 37.0
Java
import java.util.Scanner;public class FahrenheitToCelsius { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter temperature in Fahrenheit: "); double fahrenheit = scanner.nextDouble(); double celsius = (fahrenheit - 32) * 5 / 9; System.out.println("Temperature in Celsius: " + celsius); }}
Output
Enter temperature in Fahrenheit: 98.6Temperature in Celsius: 37.0
.NET
using System;class FahrenheitToCelsius{ static void Main(string[] args) { Console.Write("Enter temperature in Fahrenheit: "); double fahrenheit = double.Parse(Console.ReadLine()); double celsius = (fahrenheit - 32) * 5 / 9; Console.WriteLine("Temperature in Celsius: " + celsius); }}
Output
Enter temperature in Fahrenheit: 98.6Temperature in Celsius: 37
12. Write a program to find the sum of all the prime numbers between 1 and N.
Ans. Python
def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return Truedef sum_of_primes(n): prime_sum = 0 for num in range(2, n + 1): if is_prime(num): prime_sum += num return prime_sum# Example usagewhile True: try: user_input = input("Enter a number N: ") if user_input.strip() == "": print("No input provided. Please enter a number.") continue N = int(user_input) break except ValueError: print("Invalid input. Please enter an integer.") except EOFError: print("\nExiting the program.") breakif 'N' in locals(): print("Sum of prime numbers between 1 and", N, "is:", sum_of_primes(N))
Output
Enter a number N: Exiting the program.
Java
import java.util.Scanner;public class SumOfPrimes { 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 int sumOfPrimes(int n) { int primeSum = 0; for (int num = 2; num <= n; num++) { if (isPrime(num)) { primeSum += num; } } return primeSum; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number N: "); int N = scanner.nextInt(); System.out.println("Sum of prime numbers between 1 and " + N + " is: " + sumOfPrimes(N)); }}
Output
Enter a number N: 20Sum of prime numbers between 1 and 20 is: 77
.NET
using System;class SumOfPrimes{ public static bool 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 int SumOfPrimes(int n) { int primeSum = 0; for (int num = 2; num <= n; num++) { if (IsPrime(num)) { primeSum += num; } } return primeSum; } static void Main(string[] args) { Console.Write("Enter a number N: "); int N = int.Parse(Console.ReadLine()); Console.WriteLine("Sum of prime numbers between 1 and " + N + " is: " + SumOfPrimes(N)); }}
Output
Enter a number N: 20Sum of prime numbers between 1 and 20 is: 77
13. Write a program to make the largest number from the digits of the array.
Ans.
Python
def largest_number_from_digits(arr): arr.sort(reverse=True) return int(''.join(map(str, arr)))# Example usagearr = [3, 30, 34, 5, 9]largest_num = largest_number_from_digits(arr)print("Largest number:", largest_num)
Output
Largest number: 9534330
Java
import java.util.Arrays;import java.util.Comparator;public class LargestNumberFromArray { public static String largestNumberFromDigits(int[] arr) { String[] strArr = Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new); Arrays.sort(strArr, new Comparator<String>() { @Override public int compare(String a, String b) { String order1 = a + b; String order2 = b + a; return order2.compareTo(order1); } }); StringBuilder sb = new StringBuilder(); for (String s : strArr) { sb.append(s); } return sb.toString(); } public static void main(String[] args) { int[] arr = {3, 30, 34, 5, 9}; String largestNum = largestNumberFromDigits(arr); System.out.println("Largest number: " + largestNum); }}
Output
Largest number: 9534330
.NET
using System;using System.Linq;class LargestNumberFromArray{ static string LargestNumberFromDigits(int[] arr) { Array.Sort(arr, (a, b) => (b.ToString() + a.ToString()).CompareTo(a.ToString() + b.ToString())); return string.Join("", arr); } static void Main(string[] args) { int[] arr = { 3, 30, 34, 5, 9 }; string largestNum = LargestNumberFromDigits(arr); Console.WriteLine("Largest number: " + largestNum); }}
Output
Largest number: 9534330
10 Infosys Coding Questions For Specialist Programmer 2024
1. 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.
Ans.
def triangle_sum(arr): # Start with the given array as the last row of the triangle current_row = arr[:] triangle = [current_row] # Build the triangle from the bottom up while len(current_row) > 1: next_row = [current_row[i] + current_row[i + 1] for i in range(len(current_row) - 1)] triangle.append(next_row) current_row = next_row # Print the triangle for row in reversed(triangle): print(row) # Example usagearr = [4, 7, 3, 6, 7]triangle_sum(arr)
Output
[81][40, 41][21, 19, 22][11, 10, 9, 13][4, 7, 3, 6, 7]
2. Given the stock price of the day. Find the maximum profit you can earn by selling them.
Ans.
def max_profit(prices): if not prices: return 0 # Initialize variables to store the minimum price and maximum profit min_price = prices[0] max_profit = 0 for price in prices: # Update the minimum price if the current price is lower if price < min_price: min_price = price # Calculate the profit if the current price is sold and update the maximum profit profit = price - min_price if profit > max_profit: max_profit = profit return max_profit# Example usageprices = [7, 1, 5, 3, 6, 4]print("Maximum profit:", max_profit(prices))
Output
Maximum profit: 5
3. You are given a matrix that contains only 0 and 1 find the maximum size of a rectangle that contains only
Ans.
def maximal_rectangle(matrix): if not matrix or not matrix[0]: return 0 n = len(matrix) m = len(matrix[0]) # Initialize the heights array for histogram heights = [0] * m max_area = 0 for row in matrix: for i in range(m): # Update the current height of histogram bars heights[i] = heights[i] + 1 if row[i] == '1' else 0 # Update the maximum area using the largest rectangle in histogram max_area = max(max_area, largest_rectangle_area(heights)) return max_areadef largest_rectangle_area(heights): stack = [] max_area = 0 index = 0 while index < len(heights): # Push the current bar to stack if it is higher than the bar at stack top if not stack or heights[index] >= heights[stack[-1]]: stack.append(index)
Output
Maximum size of rectangle containing only 1's: 6
4. Given the coordinates of the endpoints of two rectangles find whether they overlap each other or not.
Ans.
def do_rectangles_overlap(x1, y1, x2, y2, x3, y3, x4, y4): # Check if one rectangle is to the left of the other if x2 < x3 or x4 < x1: return False # Check if one rectangle is above the other if y2 < y3 or y4 < y1: return False return True# Example usagex1, y1, x2, y2 = 0, 0, 2, 2 # Rectangle 1 coordinatesx3, y3, x4, y4 = 1, 1, 3, 3 # Rectangle 2 coordinatesif do_rectangles_overlap(x1, y1, x2, y2, x3, y3, x4, y4): print("The rectangles overlap.")else: print("The rectangles do not overlap.")
Output
The rectangles overlap.
5. You are given two strings to find whether we can convert one string to another by rotating in two places.
Ans.
def can_obtain_by_rotation(s1, s2): # Ensure the lengths are the same and are greater than 2 if len(s1) != len(s2) or len(s1) <= 2: return False # Clockwise rotation clockwise = s2[-2:] + s2[:-2] # Anticlockwise rotation anticlockwise = s2[2:] + s2[:2] return s1 == clockwise or s1 == anticlockwise# Test casess1 = "amazon"s2 = "onamaz"print(can_obtain_by_rotation(s1, s2)) # True, because s1 can be obtained by anticlockwise rotating s2 by 2 placess1 = "amazon"s2 = "azonam"print(can_obtain_by_rotation(s1, s2)) # True, because s1 can be obtained by clockwise rotating s2 by 2 placess1 = "hello"s2 = "lohel"print(can_obtain_by_rotation(s1, s2)) # False, as s1 can't be obtained by rotating s2 by 2 places
Output
TrueTrueFalse
6. You are given two strings to find whether we can convert one string to another by rotating in two places.
Ans.
def can_obtain_by_rotation(s1, s2): # Ensure the lengths are the same and are greater than 2 if len(s1) != len(s2) or len(s1) < 2: return False # Clockwise rotation: move last two characters to the front clockwise = s2[-2:] + s2[:-2] # Anticlockwise rotation: move first two characters to the end anticlockwise = s2[2:] + s2[:2] # Check if s1 matches either of the rotations return s1 == clockwise or s1 == anticlockwise# Test casess1 = "amazon"s2 = "onamaz"print(can_obtain_by_rotation(s1, s2)) # Expected output: Trues1 = "amazon"s2 = "azonam"print(can_obtain_by_rotation(s1, s2)) # Expected output: Trues1 = "hello"s2 = "lohel"print(can_obtain_by_rotation(s1, s2)) # Expected output: False
Output
TrueTrueFalse
7. There areNbuckets numbered11throughN. The buckets contain balls; each ball has a color between11andK. Let’s denote the number of balls with the colorj, initially in bucket i, by, ai,j.
For eachifrom1toN−1(in this order), someone throws a ball uniformly from bucketiand puts it into bucketi+1, then continues to draw the next ball. After throwing a ball in bucketN, this person draws a ball, again uniformly at random, from bucketN.
For each color from1toK, find the probability that the ball drawn from bucketNhas this color.
Output
Print a single line containingKspace-separated real numbers. For each validi, thei-th of these numbers should denote the probability that the last drawn ball has colori. Your answer will be considered correct if an absolute or relative error does not exceed10^6
Ans.
def probability_color_from_bucket_N(N, K, ai, pi): total_balls_N = sum(ai[N-1]) # Total number of balls in bucket N probabilities = [0] * K # Initialize probabilities for each color for j in range(1, K+1): # For each color j color_probability_N = 0 for i in range(N-1): # Iterate through buckets 1 to N-1 # Probability of drawing color j from bucket i and transferring it to bucket i+1 color_probability_N += pi[i][j-1] * ai[i][j-1] / total_balls_N probabilities[j-1] = color_probability_N return probabilities# Example usage:N = 5 # Number of bucketsK = 3 # Number of colorsai = [[2, 1, 3], [4, 2, 1], [3, 3, 2], [1, 2, 1], [2, 1, 3]] # Number of balls initially in each bucketpi = [[0.2, 0.4, 0.4], [0.3, 0.5, 0.2], [0.4, 0.3, 0.3], [0.1, 0.6, 0.3]] # Probability of drawing each color from each bucketprobabilities = probability_color_from_bucket_N(N, K, ai, pi)for j, prob in enumerate(probabilities, 1): print(f"Probability of drawing color {j} from bucket N: {prob}")
Output
0.3333333333333333 0.6666666666666666
8. Khaled has an array of A of N elements. It is guaranteed that N is even.He wants to choose at most N/2 elements from array A. It is not necessary to elements.Khaled is interested in XOR of all the elements he chooses. Here, XOR denotes the bitwise XOR operation.
- If A=[2,4,6,8], then Khaled can choose the subset [2,4,8] to achieve XOR=(2 XOR 4 XOR 8)=14.
Khaled wants to maximize the XOR of all the elements he chooses. Your task is to help Khaled to find the max XOR of a subset that he can achieve by choosing at most N/2 elements.
Input format
- The first line contains an integer, N, denoting the number of elements in A.
- Each line i of the N subsequent lines(where 0<=i<=N) contains an integer describing Ai
Ans.
def max_subset_xor(N, A): max_xor = 0 mask = 0 # Iterate over each bit position from left to right for i in range(31, -1, -1): mask |= (1 << i) # Set the ith bit in mask # Initialize a set to store the prefixes of elements' XOR results prefixes = set() curr_max_xor = max_xor | (1 << i) # Update the potential max XOR with the current bit # Iterate over each element in the array for num in A: prefixes.add(num & mask) # Calculate the prefix of num based on the mask # Try to update the max XOR with the current bit for prefix in prefixes: if (curr_max_xor ^ prefix) in prefixes: max_xor = curr_max_xor break return max_xor# Input processingN = int(input())A = [int(input()) for _ in range(N)]# Calculate the max XOR of the subsetresult = max_subset_xor(N, A)print(result)
9. You have an arrayAofNintegersA1A2 .. An. Find the longest increasing subsequenceAi1 Ai2 .. Ak
(1 <= k <= N) that satisfies the following condition:
For every adjacent pair of numbers of the chosen subsequenceAi[x]andAi[x+1](1 < x < k),the expression(Ai[x]&Ai[x+1]) * 2 < (Ai[x]|Ai[x+1]) is true
Note: ‘&’ is the bitwise AND operation, ‘ | ‘ is the bit-wise OR operation
Input Format
- The first line contains an integer, N, denoting the number of elements in A.
- Each line i of the N subsequent lines (where 0 ≤ i < N) contains an integer describing Ai.
Ans.
def Sequence(arr, i, n, prev=0): if i == n: return 0 x = Sequence(arr, i + 1, n, prev) y = 0 if arr[i] > prev: y = 1 + Sequence(arr, i + 1, n, arr[i]) return max(y, x)n = int(input())arr = []for i in range(n):
10. Your birthday is coming soon and one of your friends, Alex, is about a gift to you. He knows that you like integer arrays with interesting properties.
He selected two numbers,NandK, and plans to write down on paper all integer arrays of lengthK(in forma[1], a[2], …, a[K]), where every numbera[i]is in range from1toN, anda[i+1]is divisible bya[i](where 1 <i<=K), and give you this paper as a birthday present.
Alex is very patient, so he managed to do this. Now you’re wondering, how many different arrays are written down on this paper?
Ans.
def counter(n, k): num = 0 if k == 1: return n else: for i in range(1, n + 1): for j in range(1, n + 1): if j % i == 0: num += 1 return num def count(n, k): if k == 1: return n if k == 2: return counter(n, k) mid = k // 2 x = count(n, k - mid) y = counter(n, mid) return x + y - 1 n = int(input())k = int(input())print(count(n, k))
In the Infosys coding question, the task was to find the longest increasing subsequence in an array that satisfies a specific bitwise condition between adjacent elements. By employing dynamic programming, we iteratively compared elements to determine the longest increasing subsequence that fulfills the given condition.
This approach ensured efficiency and accuracy in identifying the desired subsequence. Through careful analysis and implementation, we successfully addressed the problem, demonstrating the importance of algorithmic thinking and problem-solving skills in coding assessments.
Important Links- Infosys Coding Questions
- Infosys Hiring 2024- Infosys Exam Date, Eligibility Criteria, Exam Pattern
- Infosys Exam Syllabus and Exam Pattern 2024 – PDF Download
- Infosys Application Form 2024-Apply Now, Application Link
- Infosys Eligibility Criteria For Freshers And Experienced 2024
- Infosys Salary For Freshers And Experienced in 2024
- How to Prepare For Infosys Exam 2024- Tips and Strategies
- Infosys Previous Year Paper-Download PDF With Answers
Infosys Coding Questions- FAQs
Q1. What type of coding questions are asked in Infosys?
Ans. C function to Swap strings, Conversion of whole String to uppercase or lowercase using STL in C++, and Minimum number whose binary form is not a subsequence of a given binary string
Q2.What language is used in Infosys programming?
Ans. Python, Java, or .Net are the languages used in the Infosys programming.
Q3. Is there any coding round in Infosys?
Ans. Infosys usually has three rounds of coding interviews. First, there’s an online test where you solve coding problems. Next is the technical round, where they ask about technical coding.
Q4. What are Infosys coding questions?
Ans. Infosys coding questions are problems or puzzles related to programming that candidates are asked to solve during the recruitment process.
Q5.How should I prepare for Infosys coding questions?
Ans. To prepare for Infosys coding questions- practice coding regularly, and solve coding problems available on the Infosys mock test of Skillvertex. This will improve your skills and knowledge of data structures and algorithms.
Q6. Are Infosys coding questions challenging?
Ans. Infosys coding questions can vary in difficulty, ranging from easy to moderate difficulty levels. Some questions require basic problem-solving skills, while others may involve more complex algorithms and data structures.
Q7. Is it necessary to have coding experience to succeed in Infosys coding interviews?
Ans. Prior coding experience can be beneficial and is not required to succeed in Infosys coding interviews. Candidates can perform well with continuous practice and a solid understanding of fundamental programming concepts.
Q8.Can I use any programming language for solving Infosys coding questions?
Ans. No, for solving Infosys coding questions – Java, Python,.NET are used.
Hridhya Manoj
Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together