0% found this document useful (0 votes)
45 views18 pages

Top Infosys Coding Questions and Answers

Uploaded by

tjagan42
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
45 views18 pages

Top Infosys Coding Questions and Answers

Uploaded by

tjagan42
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

Top Infosys Coding Questions and

Answers (2024)

Q.1 - How do you swap two arrays in C++?

om
Answer:

Sample Input

A[ ] = {21, 22, 23, 24}

.c
B[ ] = {25, 26, 27, 28}

er
Sample Output

A[ ] = {25, 26, 27, 28}


B[ ] = {21, 22, 23, 24}
rn
C++ Code:
ea

#include <iostream>
using namespace std;

void swapArrays(int* a, int* b, int size) {


el

for (int i = 0; i < size; i++) {


int temp = a[i];
a[i] = b[i];
od

b[i] = temp;
}
}

int main() {
Cc

int a[] = {21, 22, 23, 24};


int b[] = {25, 26, 27, 28};
int n = sizeof(a)/sizeof(a[0]);

swapArrays(a, b, n);

cout << "a[] = ";


for (int i = 0; i < n; i++)
cout << a[i] << ", ";
cout << "\nb[] = ";
for (int i = 0; i < n; i++)
cout << b[i] << ", ";
return 0;
}

Output

A[ ] = {25, 26, 27, 28}


B[ ] = {21, 22, 23, 24}

om
Q.2 - Write a program to arrange the given numbers to form the
biggest number
Answer:

.c
Sample Input

er
{5, 67, 2, 88, 9, 76, 52, 4}
rn
C++

#include <iostream>
#include <vector>
ea

#include <algorithm>
using namespace std;

// Custom comparator to decide which concatenation forms a larger number


struct Comparator {
el

bool operator()(int a, int b) {


string ab = to_string(a) + to_string(b);
string ba = to_string(b) + to_string(a);
od

return ab > ba;


}
};

int main() {
Cc

vector<int> nums = {5, 67, 2, 88, 9, 76, 52, 4};


sort(nums.begin(), nums.end(), Comparator());

for (int num : nums) {


cout << num;
}
cout << endl;
return 0;
}

Java
import java.util.*;

public class LargestNumberSimple {

public static void main(String[] args) {


// Input array of integers
String[] numbers = {"5", "67", "2", "88", "9", "76", "52", "4"};

// Sort the array using a custom Comparator


Arrays.sort(numbers, new Comparator<String>() {

om
public int compare(String a, String b) {
// Compare two concatenations to decide which should come first
return (b + a).compareTo(a + b);
}
});

.c
// Check for a case where the largest number is 0
if (numbers[0].equals("0")) {
System.out.println("0");

er
return;
}

// Concatenate the sorted numbers


rn
String largestNumber = "";
for (String num : numbers) {
largestNumber += num;
}
ea

// Print the largest number


System.out.println(largestNumber);
}
el

Python
od

def largestNumber(arr):
# Convert integers to strings to enable custom sorting
arr = sorted(map(str, arr), key=lambda x: x*10, reverse=True)
# Join and return the sorted array, handling leading zeros
Cc

result = ''.join(arr)
return result if result[0] != '0' else '0'

# New input array


arr = [5, 67, 2, 88, 9, 76, 52, 4]
print(largestNumber(arr))

Output

988766752452
Q.3 - Find the smallest and largest number in an Array
Answer:

Sample Input

[3, 1, 56, 34, 12, 9, 98, 23, 4]

om
C++ Code:

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

.c
int main() {
vector<int> arr = {3, 1, 56, 34, 12, 9, 98, 23, 4};

er
int minVal = arr[0];
int maxVal = arr[0];

for(int i = 1; i < arr.size(); i++) {


rn
if(arr[i] > maxVal) maxVal = arr[i];
if(arr[i] < minVal) minVal = arr[i];
}
ea

cout << "Smallest Number: " << minVal << endl;


cout << "Largest Number: " << maxVal << endl;

return 0;
el

Java Code:
od

public class Main {


public static void main(String[] args) {
int[] arr = {3, 1, 56, 34, 12, 9, 98, 23, 4};
int minVal = arr[0];
Cc

int maxVal = arr[0];

for(int i = 1; i < arr.length; i++) {


if(arr[i] > maxVal) maxVal = arr[i];
if(arr[i] < minVal) minVal = arr[i];
}

System.out.println("Smallest Number: " + minVal);


System.out.println("Largest Number: " + maxVal);
}
}
Python Code:

arr = [3, 1, 56, 34, 12, 9, 98, 23, 4]


minVal = min(arr)
maxVal = max(arr)

print(f"Smallest Number: {minVal}")


print(f"Largest Number: {maxVal}")

Output

om
Smallest Number: 1
Largest Number: 98

.c
Q.4 - Find the next permutation of the given string in C++

er
Answer:

Sample Input
rn
s=”dcd”

C++ Code:
ea

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

void swap(char* a, char* b) {


if (*a == *b)
return;
od

*a ^= *b;
*b ^= *a;
*a ^= *b;
}
Cc

void reverseString(string& s, int start, int end) {


while (start < end) {
swap(s[start], s[end]);
start++;
end--;
}
}

bool nextPermutation(string& s) {
int n = s.length();
int i = n - 2;
while (i >= 0 && s[i] >= s[i + 1])
i--;
if (i < 0)
return false;
int j = n - 1;
while (s[j] <= s[i])
j--;
swap(s[i], s[j]);
reverseString(s, i + 1, n - 1);

om
return true;
}

int main() {
string s = "dcd"; // Sample Input
bool val = nextPermutation(s);

.c
if (!val)
cout << "No next permutation possible" << endl;
else

er
cout << "Next permutation: " << s << endl;
return 0;
}
rn
Output

Next permutation: ddc


ea

Q.5 How do you rotate a matrix by 90 degrees? Write a program.


el

Answer:

Sample Input:
od

123
456
789
Cc

C++ Code:

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

void rotateMatrix(vector<vector<int>>& matrix) {


int n = matrix.size();
// Transpose the matrix
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}
// Reverse each row
for (int i = 0; i < n; ++i) {
int left = 0, right = n - 1;
while (left < right) {
swap(matrix[i][left], matrix[i][right]);

om
left++;
right--;
}
}
}

.c
int main() {
// Input matrix
vector<vector<int>> matrix = {{1, 2, 3},

er
{4, 5, 6},
{7, 8, 9}};

// Print original matrix


rn
cout << "Original Matrix:" << endl;
for (const auto& row : matrix) {
for (int val : row) {
cout << val << " ";
ea

}
cout << endl;
}
el

// Rotate matrix
rotateMatrix(matrix);
od

// Print rotated matrix


cout << "Rotated Matrix:" << endl;
for (const auto& row : matrix) {
for (int val : row) {
cout << val << " ";
Cc

}
cout << endl;
}

return 0;
}

Java Code:

import java.util.Arrays;
public class RotateMatrix {
public static void rotateMatrix(int[][] matrix) {
int n = matrix.length;
// Transpose the matrix
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}

om
}
// Reverse each row
for (int i = 0; i < n; ++i) {
int left = 0, right = n - 1;
while (left < right) {
int temp = matrix[i][left];

.c
matrix[i][left] = matrix[i][right];
matrix[i][right] = temp;
left++;

er
right--;
}
}
}
rn
public static void main(String[] args) {
// Input matrix
int[][] matrix = {{1, 2, 3},
ea

{4, 5, 6},
{7, 8, 9}};

// Print original matrix


el

System.out.println("Original Matrix:");
for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
od

// Rotate matrix
rotateMatrix(matrix);
Cc

// Print rotated matrix


System.out.println("Rotated Matrix:");
for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
}
}
}

Python Code:

def rotate_matrix(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i] = matrix[i][::-1]

# Input matrix

om
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

# Print original matrix


print("Original Matrix:")

.c
for row in matrix:
print(row)

er
# Rotate matrix
rotate_matrix(matrix)

# Print rotated matrix


rn
print("Rotated Matrix:")
for row in matrix:
print(row)
ea

Output:

Rotated Matrix:
el

741
852
od

963

Also Read: 20 IBM Coding Questions with Answers (Assessment by Expert)


Cc

Q.6 How do you find the missing characters to make a string pangram?
Write a program
Answer:

Sample Input: "A quick movement of the enemy will jeopardize six gunboats"
C++ Code:

#include <iostream>
#include <string>
#include <unordered_set>
#include <algorithm>

std::string findMissingCharacters(const std::string& s) {


std::unordered_set<char> alphabets;
for (char c = 'a'; c <= 'z'; ++c) {
alphabets.insert(c);

om
}

for (char c : s) {
alphabets.erase(tolower(c));
}

.c
std::string missing;
for (char c : alphabets) {

er
missing.push_back(c);
}

std::sort(missing.begin(), missing.end());
rn
return missing;
}

int main() {
ea

std::string str = "A quick movement of the enemy will jeopardize six gunboats";
std::cout << "Missing characters: " << findMissingCharacters(str) << std::endl;
return 0;
}
el

Java Code:

import java.util.HashSet;
od

import java.util.Set;

public class PangramChecker {


public static String findMissingCharacters(String s) {
Cc

Set<Character> alphabets = new HashSet<>();


for (char c = 'a'; c <= 'z'; c++) {
alphabets.add(c);
}

for (char c : s.toLowerCase().toCharArray()) {


alphabets.remove(c);
}

StringBuilder missing = new StringBuilder();


for (char c : alphabets) {
missing.append(c);
}

return missing.toString();
}

public static void main(String[] args) {


String str = "A quick movement of the enemy will jeopardize six gunboats";
System.out.println("Missing characters: " + findMissingCharacters(str));
}

om
}

Python Code:

def find_missing_characters_for_pangram(s):
alphabets = set('abcdefghijklmnopqrstuvwxyz')
for char in s.lower():

.c
alphabets.discard(char)
return ''.join(sorted(alphabets))

er
# Example usage
string = "A quick movement of the enemy will jeopardize six gunboats"
missing_characters = find_missing_characters_for_pangram(string)
rn
print("Missing characters:", missing_characters)

Output
ea

"Missing characters: flr"


el

Q.7 How do you find the number of unique characters in a given


string? Write a program
od

Answer:

Sample Input: "Hello, World!"


Cc

C++ Code:

#include <iostream>
#include <unordered_set>

int countUniqueCharacters(const std::string& str) {


std::unordered_set<char> uniqueChars;
for (char c : str) {
uniqueChars.insert(c);
}
return uniqueChars.size();
}

int main() {
std::string input = "Hello, World!";
std::cout << "Number of unique characters: " << countUniqueCharacters(input) <<
std::endl;
return 0;
}

Java Code:

om
import java.util.HashSet;
import java.util.Set;

public class UniqueCharacterCounter {


public static int countUniqueCharacters(String str) {

.c
Set<Character> uniqueChars = new HashSet<>();
for (char c : str.toCharArray()) {

er
uniqueChars.add(c);
}
return uniqueChars.size();
}
rn
public static void main(String[] args) {
String input = "Hello, World!";
System.out.println("Number of unique characters: " + countUniqueCharacters(input));
ea

}
}

Python Code:
el

def count_unique_characters(s):
return len(set(s))
od

# Example usage
input_string = "Hello, World!"
unique_character_count = count_unique_characters(input_string)
print("Number of unique characters:", unique_character_count)
Cc

Output

Number of unique characters is 10.

Q.8 Write a Program for the Subtraction of Two Matrices


Answer:
Sample Input:

a)
12
34

b)
43
21

om
C++ Code:

#include <iostream>
#include <vector>

.c
std::vector<std::vector<int>> subtractMatrices(const std::vector<std::vector<int>>& A, const
std::vector<std::vector<int>>& B) {

er
std::vector<std::vector<int>> result(A.size(), std::vector<int>(A[0].size()));
for (size_t i = 0; i < A.size(); ++i) {
for (size_t j = 0; j < A[0].size(); ++j) {
result[i][j] = A[i][j] - B[i][j];
rn
}
}
return result;
}
ea

int main() {
std::vector<std::vector<int>> A = {{1, 2}, {3, 4}};
std::vector<std::vector<int>> B = {{4, 3}, {2, 1}};
std::vector<std::vector<int>> result = subtractMatrices(A, B);
el

for (const auto& row : result) {


for (int val : row) {
od

std::cout << val << " ";


}
std::cout << std::endl;
}
return 0;
Cc

Java Code:

public class MatrixSubtraction {


public static int[][] subtractMatrices(int[][] A, int[][] B) {
int[][] result = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[0].length; j++) {
result[i][j] = A[i][j] - B[i][j];
}
}
return result;
}

public static void main(String[] args) {


int[][] A = {{1, 2}, {3, 4}};
int[][] B = {{4, 3}, {2, 1}};
int[][] result = subtractMatrices(A, B);

for (int[] row : result) {

om
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
}

.c
}

Python Code:

er
def subtract_matrices(A, B):
return [[A[i][j] - B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
rn
# Example usage
A = [[1, 2], [3, 4]]
B = [[4, 3], [2, 1]]
result = subtract_matrices(A, B)
ea

for row in result:


print(" ".join(map(str, row)))
el

Output

-3 -1
od

1 3

Q.9 How do you multiply two matrices and show results through
Cc

another matrix? Write a program


Answer:

A:
12
34

B:
56
78

C++ Code:

#include <iostream>
#include <vector>

std::vector<std::vector<int>> multiplyMatrices(const std::vector<std::vector<int>>& A, const


std::vector<std::vector<int>>& B) {
size_t rows = A.size();

om
size_t cols = B[0].size();
size_t common = B.size();
std::vector<std::vector<int>> result(rows, std::vector<int>(cols, 0));

for (size_t i = 0; i < rows; ++i) {


for (size_t j = 0; j < cols; ++j) {

.c
for (size_t k = 0; k < common; ++k) {
result[i][j] += A[i][k] * B[k][j];
}

er
}
}
return result;
rn
}

int main() {
std::vector<std::vector<int>> A = {{1, 2}, {3, 4}};
ea

std::vector<std::vector<int>> B = {{5, 6}, {7, 8}};


std::vector<std::vector<int>> result = multiplyMatrices(A, B);

for (const auto& row : result) {


for (int val : row) {
el

std::cout << val << " ";


}
std::cout << std::endl;
od

}
return 0;
}

Java Code:
Cc

public class MatrixMultiplication {


public static int[][] multiplyMatrices(int[][] A, int[][] B) {
int rows = A.length;
int cols = B[0].length;
int common = B.length;
int[][] result = new int[rows][cols];

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
for (int k = 0; k < common; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
}

public static void main(String[] args) {


int[][] A = {{1, 2}, {3, 4}};
int[][] B = {{5, 6}, {7, 8}};

om
int[][] result = multiplyMatrices(A, B);

for (int[] row : result) {


for (int val : row) {
System.out.print(val + " ");
}

.c
System.out.println();
}
}

er
}

Python Code:
rn
def multiply_matrices(A, B):
rows_A, cols_A = len(A), len(A[0])
rows_B, cols_B = len(B), len(B[0])
result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]
ea

for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
el

result[i][j] += A[i][k] * B[k][j]


return result
od

# Example usage
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
result = multiply_matrices(A, B)
Cc

for row in result:


print(" ".join(map(str, row)))

Output

The output of multiplying the given matrices A and B is:

19 22
43 50
Q.10 How do you convert decimal numbers to binary numbers? Write
a Program
Answer:

Sample Input: 29

C++ Code

#include <iostream>

om
#include <string>
#include <algorithm>

std::string decimalToBinary(int n) {
std::string binary = "";
while (n > 0) {

.c
binary += std::to_string(n % 2);
n /= 2;

er
}
std::reverse(binary.begin(), binary.end());
return binary;
}
rn
int main() {
int decimal = 29;
std::cout << "Binary of " << decimal << " is " << decimalToBinary(decimal) << std::endl;
ea

return 0;
}

Java Code:
el

public class DecimalToBinary {


public static String decimalToBinary(int n) {
StringBuilder binary = new StringBuilder();
od

while (n > 0) {
binary.insert(0, n % 2);
n /= 2;
}
Cc

return binary.toString();
}

public static void main(String[] args) {


int decimal = 29;
System.out.println("Binary of " + decimal + " is " + decimalToBinary(decimal));
}
}

Python Code:
def decimal_to_binary(n):
binary = ""
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary

# Example usage
decimal = 29
binary = decimal_to_binary(decimal)

om
print(f"Binary of {decimal} is {binary}")

Output

The binary representation of the decimal number 29 is '11101’.

.c
er
Follow Us on Facebook for Latest Updates.
rn
ea
el
od
Cc

You might also like