- Practice common Infosys coding questions in algorithms, data structures, and math for interviews.
- Covers easy (sorting), medium (DP, greedy), and hard (graphs) questions with solutions in C, C++, Java, and Python.
- Focus on C++, Java, Python for DSA; tips for efficient coding.
- Helps overcome interview stress by providing practice questions, solutions, and tips.
- Boost your coding skills with real examples and strategies to ace Infosys assessments.
Preparing for Infosys interviews can feel overwhelming, but understanding the types of coding questions asked is a great start. Infosys, a leading IT company, tests candidates on problem-solving and coding skills to find those who can handle real-world tech tasks. This blog covers common coding questions, their difficulty levels, and solutions in simple languages. By the end, you'll have tips to practice and succeed.
Traditional coding prep often focuses on theory, but Infosys wants practical skills. Many students struggle with applying concepts under time pressure. This blog solves that by offering questions, answers, and strategies to build confidence.
The Changing Landscape of Coding Interviews
Coding interviews have changed from simple puzzles to real-world problems. Infosys now tests how candidates solve tasks like optimizing data or building secure systems. This shift means students need practice with actual questions to succeed.
Why Coding Matters: Coding tests show your ability to think logically and write clean code, key for tech jobs
1. Algorithm-based Questions
- Sorting Algorithms (e.g., Quick Sort, Merge Sort)
- Searching Algorithms (e.g., Binary Search, Linear Search)
- Dynamic Programming (e.g., Fibonacci, Knapsack Problem)
- Greedy Algorithms (e.g., Activity Selection)
- Backtracking (e.g., N-Queens Problem)
2. Data Structure Questions
- Arrays (e.g., Rotation, Merging)
- Linked Lists (e.g., Reversal, Cycle Detection)
- Stacks (e.g., Parenthesis Matching)
- Queues (e.g., Implementing with Stacks)
- Trees (e.g., Traversal, Height Calculation)
- Graphs (e.g., BFS, DFS)
3. String Manipulation
- String Reversal
- Anagram Checking
- Substring Search (e.g., Rabin-Karp Algorithm)
- Palindrome Checking
- Character Counting
4. Mathematical Problems
- Prime Number Generation (e.g., Sieve of Eratosthenes)
- Factorial Calculation
- Fibonacci Sequence
- GCD and LCM Calculations
- Combinatorial Problems (e.g., Pascal's Triangle)
While preparing coding interviews or competitive programming, the fluctuation of the difficulty level of coding questions is one of the major problems that candidates put their hands on. Normally, such questions are divided into three groups: easy, medium, and hard. The difficulty level indicates not only the problem's complexity but also the depth of the algorithmic concepts needed to be applied. Today, we are going to delve into the classification of coding questions and explain the words that you will probably come across in these different levels.
Easy Level Questions
Easy level questions are generally aimed at checking your elementary programming knowledge along with your grasp of the basic concepts. Such problems can be about using simple data structures like arrays, strings, and linked lists. The main point is to measure your skill in writing efficient and readable code for the given algorithms.
At this stage, candidates are expected to demonstrate proficiency in:
- Basic loops and conditionals
- Array manipulations
- String operations
These questions are often solved through direct implementation without the need for advanced algorithmic knowledge. You might encounter problems like finding the maximum or minimum in an array or reversing a string.
Medium Level Questions
Medium level questions bring in more complexity, thus, candidates have to show the application of advanced concepts. Most of the time, they require the use of dynamic programming (DP) or greedy algorithms. These kinds of challenges don't only check your knowledge of data structures but also your skill in problem breakdown and coming up with efficient algorithms.
- Dynamic Programming: DP problems typically involve solving sub-problems and building up to a final solution, often by storing intermediate results to avoid redundant calculations. Common medium-level questions include problems like the 0/1 knapsack problem or longest common subsequence.
- Greedy Algorithms: Greedy problems ask you to make locally optimal choices at each step in the hope of finding the global optimum. Examples include interval scheduling, activity selection problems, and problems where you have to choose the most optimal solution step by step.
In the medium difficulty range, you might encounter:
- Orthogonal Greedy Algorithms: These problems use a combination of greedy techniques and sometimes divide and conquer or DP. The idea is to solve a problem by breaking it into independent, non-overlapping sub-problems.
- Pure Greedy Algorithms: This involves problems that can be solved by taking the best possible decision at each step, without revisiting previous steps (e.g., coin change problem).
- Relaxed Greedy Algorithms: These problems allow a more relaxed approach to greedy techniques, sometimes involving a heuristic or approximation when an exact solution is too expensive to compute.
Hard Level Questions
Usually, hard level questions demand the candidates to thoroughly understand advanced algorithmic techniques. Such problems generally entail the combination of several concepts, and thus the resolution of these problems needs to be inventive and the candidates to have excellent problem-solving skills.
The solutions to these problems might require advanced dynamic programming techniques, optimization methods, or in-depth knowledge of complex data structures. Examples include:
- Graph algorithms (e.g., Dijkstra’s, Bellman-Ford)
- String matching algorithms
- Advanced greedy strategies
- Computational geometry
In these hard-level problems, candidates might need to:
- Utilize dynamic programming with complex state transitions.
- Apply greedy algorithms in combination with other techniques, such as backtracking or divide and conquer.
For example, the knapsack problem can become a more complex variant when combined with other constraints, requiring a hybrid approach of dynamic programming and greedy algorithms.
What We’ve Learned So Far: Infosys questions test algorithms, data structures, strings, and math—practice these to build a strong foundation.
Based on common questions from sources, here are the formatted versions of the provided coding questions. Each includes a problem statement, input format, output format, sample input and output, solutions in C, C++, Java, and Python (with codes modified for consistency to take user input where applicable), and a code explanation.
1. Swap Two Numbers Using a Temporary Variable
Problem Statement
Write a program to swap two numbers using a temporary variable.
Input Format
- First line: an integer a
- Second line: an integer b
Output Format
- Print "Before swapping: a = , b = "
- Print "After swapping: a = , b = "
Sample Input
5
10
Sample Output
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
Solutions
C
#include <stdio.h>
int main() {
int a, b, temp;
scanf("%d", &a);
scanf("%d", &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
// Swap using a temporary variable
temp = a;
a = b;
b = temp;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}C++
#include <iostream>
using namespace std;
int main() {
int a, b, temp;
cin >> a >> b;
cout << "Before swapping: a = " << a << ", b = " << b << endl;
// Swap using a temporary variable
temp = a;
a = b;
b = temp;
cout << "After swapping: a = " << a << ", b = " << b << endl;
return 0;
}Java
import java.util.Scanner;
public class SwapNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println("Before swapping: a = " + a + ", b = " + b);
// Swap using a temporary variable
int temp = a;
a = b;
b = temp;
System.out.println("After swapping: a = " + a + ", b = " + b);
scanner.close();
}
}
Python
a = int(input())
b = int(input())
print("Before swapping: a =", a)
print("Before swapping: b =", b)
# Swap using a temporary variable
temp = a
a = b
b = temp
print("After swapping: a =", a)
print("After swapping: b =", b)Explanation of Code
The program takes two integers as input. It outputs the integers as they are, performs the swap operation using a temporary variable, and then outputs the integers after swapping. This method is simple and has a constant time complexity.
2. Convert Decimal Number to Binary Number
Problem Statement
Write a program to convert a decimal number to its binary representation.
Input Format
- First line: an integer n (decimal number)
Output Format
- Print "Binary representation of <n> is: <binary>"
Sample Input
11
Sample Output
Binary representation of 11 is: 1011
Solutions
C
#include <stdio.h>
void convertToBinary(int num) {
if (num == 0) {
printf("0");
return;
}
int binary[32], i = 0;
while (num > 0) {
binary[i] = num % 2;
num /= 2;
i++;
}
// Print binary in reverse order
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
}
int main() {
int n;
scanf("%d", &n);
printf("Binary representation of %d is: ", n);
convertToBinary(n);
printf("\n");
return 0;
}C++
#include <iostream>
using namespace std;
void convertToBinary(int num) {
if (num == 0) {
cout << "0";
return;
}
int binary[32];
int i = 0;
while (num > 0) {
binary[i] = num % 2;
num /= 2;
i++;
}
// Print binary in reverse order
for (int j = i - 1; j >= 0; j--) {
cout << binary[j];
}
}
int main() {
int n;
cin >> n;
cout << "Binary representation of " << n << " is: ";
convertToBinary(n);
cout << endl;
return 0;
}Java
import java.util.Scanner;
public class DecimalToBinary {
public static void convertToBinary(int num) {
if (num == 0) {
System.out.print("0");
return;
}
StringBuilder binary = new StringBuilder();
while (num > 0) {
binary.append(num % 2);
num /= 2;
}
System.out.print(binary.reverse().toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.print("Binary representation of " + n + " is: ");
convertToBinary(n);
System.out.println();
scanner.close();
}
}Python
def convert_to_binary(num):
if num == 0:
return "0"
binary = []
while num > 0:
binary.append(str(num % 2))
num //= 2
binary.reverse()
return ''.join(binary)
n = int(input())
binary_representation = convert_to_binary(n)
print(f"Binary representation of {n} is: {binary_representation}")Explanation of Code
The program takes two integers as input. It outputs the integers as they are, performs the swap operation using a temporary variable, and then outputs the integers after swapping. This method is simple and has a constant time complexity.
3. Convert Decimal Number to Octal Number
Problem Statement
Write a program to convert a decimal number to its octal representation.
Input Format
- First line: an integer n (decimal number)
Output Format
- Print "Octal representation of <n> is: <octal>"
Sample Input
148
Sample Output
Octal representation of 148 is: 224
Solutions
C
#include <stdio.h>
void convertToOctal(int num) {
if (num == 0) {
printf("0");
return;
}
int octal[32], i = 0;
while (num > 0) {
octal[i] = num % 8;
num /= 8;
i++;
}
// Print octal in reverse order
for (int j = i - 1; j >= 0; j--) {
printf("%d", octal[j]);
}
}
int main() {
int n;
scanf("%d", &n);
printf("Octal representation of %d is: ", n);
convertToOctal(n);
printf("\n");
return 0;
}C++
#include <iostream>
using namespace std;
void convertToOctal(int num) {
if (num == 0) {
cout << "0";
return;
}
int octal[32];
int i = 0;
while (num > 0) {
octal[i] = num % 8;
num /= 8;
i++;
}
// Print octal in reverse order
for (int j = i - 1; j >= 0; j--) {
cout << octal[j];
}
}
int main() {
int n;
cin >> n;
cout << "Octal representation of " << n << " is: ";
convertToOctal(n);
cout << endl;
return 0;
}Java
import java.util.Scanner;
public class DecimalToOctal {
public static void convertToOctal(int num) {
if (num == 0) {
System.out.print("0");
return;
}
StringBuilder octal = new StringBuilder();
while (num > 0) {
octal.append(num % 8);
num /= 8;
}
System.out.print(octal.reverse().toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.print("Octal representation of " + n + " is: ");
convertToOctal(n);
System.out.println();
scanner.close();
}
}Python
def convert_to_octal(num):
if num == 0:
return "0"
octal = []
while num > 0:
octal.append(str(num % 8))
num //= 8
octal.reverse()
return ''.join(octal)
n = int(input())
octal_representation = convert_to_octal(n)
print(f"Octal representation of {n} is: {octal_representation}")Explanation of Code
The process is similar to binary conversion, the program keeps dividing the number by 8 and collects the remainders for the octal digits. The digits are reversed and printed. The time complexity is O(log n).
4. Convert Decimal Number to Hexadecimal Number
Problem Statement
Write a program to convert a decimal number to its hexadecimal representation.
Input Format
- First line: an integer n (decimal number)
Output Format
- Print "Hexadecimal representation of <n> is: <hex>"
Sample Input
1457
Sample Output
Hexadecimal representation of 1457 is: 5B1
Solutions
C
#include <stdio.h>
void convertToHexadecimal(int num) {
if (num == 0) {
printf("0");
return;
}
char hexa[100];
int i = 0;
while (num != 0) {
int rem = num % 16;
hexa[i++] = (rem < 10) ? (rem + '0') : (rem - 10 + 'A');
num /= 16;
}
// Print hexadecimal in reverse order
for (int j = i - 1; j >= 0; j--) {
printf("%c", hexa[j]);
}
}
int main() {
int decimal;
scanf("%d", &decimal);
printf("Hexadecimal representation of %d is: ", decimal);
convertToHexadecimal(decimal);
printf("\n");
return 0;
}C++
#include <iostream>
using namespace std;
void convertToHexadecimal(int num) {
if (num == 0) {
cout << "0";
return;
}
char hexa[100];
int i = 0;
while (num != 0) {
int rem = num % 16;
hexa[i++] = (rem < 10) ? (rem + '0') : (rem - 10 + 'A');
num /= 16;
}
// Print hexadecimal in reverse order
for (int j = i - 1; j >= 0; j--) {
cout << hexa[j];
}
}
int main() {
int decimal;
cin >> decimal;
cout << "Hexadecimal representation of " << decimal << " is: ";
convertToHexadecimal(decimal);
cout << endl;
return 0;
}Java
import java.util.Scanner;
public class DecimalToHexadecimal {
public static void convertToHexadecimal(int num) {
if (num == 0) {
System.out.print("0");
return;
}
StringBuilder hexa = new StringBuilder();
while (num != 0) {
int rem = num % 16;
if (rem < 10) {
hexa.append(rem);
} else {
hexa.append((char) (rem - 10 + 'A'));
}
num /= 16;
}
System.out.print(hexa.reverse().toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int decimal = scanner.nextInt();
System.out.print("Hexadecimal representation of " + decimal + " is: ");
convertToHexadecimal(decimal);
System.out.println();
scanner.close();
}
}Python
def convert_to_hexadecimal(num):
if num == 0:
return "0"
hexa = []
while num > 0:
rem = num % 16
if rem < 10:
hexa.append(str(rem))
else:
hexa.append(chr(rem - 10 + ord('A')))
num //= 8
hexa.reverse()
return ''.join(hexa)
decimal = int(input())
hexadecimal_representation = convert_to_hexadecimal(decimal)
print(f"Hexadecimal representation of {decimal} is: {hexadecimal_representation}")Explanation of Code
The program repeatedly divides by 16 and uses the remainders to get hex digits (0-9, A-F for 10-15). The digits are collected, reversed, and printed. The time complexity is O(log n).
Note: In the Python code provided originally, there was a typo (num //= 8 instead of 16); corrected here to //= 16.
5. Swap Two Numbers Without Using a Third Variable
Problem Statement
Write a program to swap two numbers without using a temporary variable.
Input Format
- First line: an integer a
- Second line: an integer b
Output Format
- Print "Before swapping: a = , b = "
- Print "After swapping: a = , b = "
Sample Input
5
10
Sample Output
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
Solutions
C
#include <stdio.h>
int main() {
int a, b;
scanf("%d", &a);
scanf("%d", &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
// Swap without using a temporary variable
a = a + b;
b = a - b;
a = a - b;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}C++
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << "Before swapping: a = " << a << ", b = " << b << endl;
// Swap without using a temporary variable
a = a + b;
b = a - b;
a = a - b;
cout << "After swapping: a = " << a << ", b = " << b << endl;
return 0;
}Java
import java.util.Scanner;
public class SwapNumbersWithoutTemp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println("Before swapping: a = " + a + ", b = " + b);
// Swap without using a temporary variable
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping: a = " + a + ", b = " + b);
scanner.close();
}
}Python
a = int(input())
b = int(input())
print("Before swapping: a =", a)
print("Before swapping: b =", b)
# Swap without using a temporary variable
a = a + b
b = a - b
a = a - b
print("After swapping: a =", a)
print("After swapping: b =", b)Explanation of Code
The program uses arithmetic operations (addition and subtraction) to swap values without extra space. This works in O(1) time but may cause overflow for large numbers.
6. Convert Octal Number to Binary Number
Problem Statement
Write a program to convert an octal number to its binary representation.
Input Format
- First line: an integer (octal number)
Output Format
- Print "Binary representation: <binary>"
Sample Input
10
Sample Output
Binary representation: 1000
Solutions
C
#include <stdio.h>
#include <math.h>
int octalToDecimal(int octal) {
int decimal = 0, base = 1;
while (octal > 0) {
int last_digit = octal % 10;
decimal += last_digit * base;
base *= 8;
octal /= 10;
}
return decimal;
}
void decimalToBinary(int decimal) {
if (decimal == 0) {
printf("0");
return;
}
int binary[32], i = 0;
while (decimal > 0) {
binary[i++] = decimal % 2;
decimal /= 2;
}
// Print binary in reverse order
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
}
int main() {
int octal;
scanf("%d", &octal);
int decimal = octalToDecimal(octal);
printf("Binary representation: ");
decimalToBinary(decimal);
printf("\n");
return 0;
}C++
#include <iostream>
using namespace std;
int octalToDecimal(int octal) {
int decimal = 0, base = 1;
while (octal > 0) {
int last_digit = octal % 10;
decimal += last_digit * base;
base *= 8;
octal /= 10;
}
return decimal;
}
void decimalToBinary(int decimal) {
if (decimal == 0) {
cout << "0";
return;
}
int binary[32];
int i = 0;
while (decimal > 0) {
binary[i++] = decimal % 2;
decimal /= 2;
}
// Print binary in reverse order
for (int j = i - 1; j >= 0; j--) {
cout << binary[j];
}
}
int main() {
int octal;
cin >> octal;
int decimal = octalToDecimal(octal);
cout << "Binary representation: ";
decimalToBinary(decimal);
cout << endl;
return 0;
}Java
import java.util.Scanner;
public class OctalToBinary {
public static int octalToDecimal(int octal) {
int decimal = 0, base = 1;
while (octal > 0) {
int lastDigit = octal % 10;
decimal += lastDigit * base;
base *= 8;
octal /= 10;
}
return decimal;
}
public static void decimalToBinary(int decimal) {
if (decimal == 0) {
System.out.print("0");
return;
}
StringBuilder binary = new StringBuilder();
while (decimal > 0) {
binary.append(decimal % 2);
decimal /= 2;
}
System.out.print(binary.reverse().toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int octal = scanner.nextInt();
int decimal = octalToDecimal(octal);
System.out.print("Binary representation: ");
decimalToBinary(decimal);
System.out.println();
scanner.close();
}
}Python
def octal_to_decimal(octal):
decimal = 0
base = 1
while octal > 0:
last_digit = octal % 10
decimal += last_digit * base
base *= 8
octal //= 10
return decimal
def decimal_to_binary(decimal):
if decimal == 0:
return "0"
binary = []
while decimal > 0:
binary.append(str(decimal % 2))
decimal //= 2
binary.reverse()
return ''.join(binary)
octal_value = int(input())
decimal_value = octal_to_decimal(octal_value)
binary_value = decimal_to_binary(decimal_value)
print(f"Binary representation: {binary_value}")Explanation of Code
The program first converts octal to decimal by multiplying digits with powers of 8, then converts decimal to binary as in question 2. Time complexity is O(log n) for each conversion.
7. Convert Octal Number to Decimal Number
Problem Statement
Write a program to convert an octal number to its decimal representation.
Input Format
- First line: an integer (octal number)
Output Format
- Print "Decimal representation: <decimal>"
Sample Input
10
Sample Output
Decimal representation: 8
Solutions
C
#include <stdio.h>
#include <math.h>
int octalToDecimal(int octal) {
int decimal = 0, base = 1;
while (octal > 0) {
int last_digit = octal % 10;
decimal += last_digit * base;
base *= 8;
octal /= 10;
}
return decimal;
}
int main() {
int octal;
scanf("%d", &octal);
int decimal = octalToDecimal(octal);
printf("Decimal representation: %d\n", decimal);
return 0;
}C++
#include <iostream>
using namespace std;
int octalToDecimal(int octal) {
int decimal = 0, base = 1;
while (octal > 0) {
int last_digit = octal % 10;
decimal += last_digit * base;
base *= 8;
octal /= 10;
}
return decimal;
}
int main() {
int octal;
cin >> octal;
int decimal = octalToDecimal(octal);
cout << "Decimal representation: " << decimal << endl;
return 0;
}Java
import java.util.Scanner;
public class OctalToDecimal {
public static int octalToDecimal(int octal) {
int decimal = 0, base = 1;
while (octal > 0) {
int lastDigit = octal % 10;
decimal += lastDigit * base;
base *= 8;
octal /= 10;
}
return decimal;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int octal = scanner.nextInt();
int decimal = octalToDecimal(octal);
System.out.println("Decimal representation: " + decimal);
scanner.close();
}
}Python
def octal_to_decimal(octal):
decimal = 0
base = 1
while octal > 0:
last_digit = octal % 10
decimal += last_digit * base
base *= 8
octal //= 10
return decimal
octal_value = int(input())
decimal_value = octal_to_decimal(octal_value)
print(f"Decimal representation: {decimal_value}")
Explanation of Code
The decimal is found by the program as it adds each octal digit times the corresponding power of 8 which is increasing. The time complexity is O(log n).
8. Spiral Traversal of a Matrix
Problem Statement
Write a program to print the spiral traversal of a given matrix.
Input Format
- First line: two integers ROW COL
- Next ROW lines: COL integers each for the matrix
Output Format
- Print "Spiral traversal of the matrix is: " followed by the elements in spiral order separated by space
Sample Input
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16Sample Output
Spiral traversal of the matrix is: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Solutions
C
#include <stdio.h>
int main() {
int ROW, COL;
scanf("%d %d", &ROW, &COL);
int arr[100][100]; // Assuming max 100x100
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
scanf("%d", &arr[i][j]);
}
}
printf("Spiral traversal of the matrix is: ");
int top = 0, bottom = ROW - 1, left = 0, right = COL - 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++)
printf("%d ", arr[top][i]);
top++;
for (int i = top; i <= bottom; i++)
printf("%d ", arr[i][right]);
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--)
printf("%d ", arr[bottom][i]);
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--)
printf("%d ", arr[i][left]);
left++;
}
}
printf("\n");
return 0;
}C++
#include <iostream>
using namespace std;
int main() {
int ROW, COL;
cin >> ROW >> COL;
int arr[100][100]; // Assuming max 100x100
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
cin >> arr[i][j];
}
}
cout << "Spiral traversal of the matrix is: ";
int top = 0, bottom = ROW - 1, left = 0, right = COL - 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++)
cout << arr[top][i] << " ";
top++;
for (int i = top; i <= bottom; i++)
cout << arr[i][right] << " ";
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--)
cout << arr[bottom][i] << " ";
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--)
cout << arr[i][left] << " ";
left++;
}
}
cout << endl;
return 0;
}Java
import java.util.Scanner;
public class SpiralTraversal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int ROW = scanner.nextInt();
int COL = scanner.nextInt();
int[][] matrix = new int[ROW][COL];
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
matrix[i][j] = scanner.nextInt();
}
}
System.out.print("Spiral traversal of the matrix is: ");
int top = 0, bottom = ROW - 1, left = 0, right = COL - 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++)
System.out.print(matrix[top][i] + " ");
top++;
for (int i = top; i <= bottom; i++)
System.out.print(matrix[i][right] + " ");
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--)
System.out.print(matrix[bottom][i] + " ");
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--)
System.out.print(matrix[i][left] + " ");
left++;
}
}
System.out.println();
scanner.close();
}
}Python
rows, cols = map(int, input().split())
matrix = []
for _ in range(rows):
matrix.append(list(map(int, input().split())))
print("Spiral traversal of the matrix is:", end=" ")
top, bottom = 0, rows - 1
left, right = 0, cols - 1
result = []
while left <= right and top <= bottom:
for i in range(left, right + 1):
result.append(str(matrix[top][i]))
top += 1
for i in range(top, bottom + 1):
result.append(str(matrix[i][right]))
right -= 1
if top <= bottom:
for i in range(right, left - 1, -1):
result.append(str(matrix[bottom][i]))
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1):
result.append(str(matrix[i][left]))
left += 1
print(' '.join(result))
Explanation of Code
While moving through layers the boundaries (top, bottom, left, right) are getting smaller: right, down, left, up. The conditions eliminate overlapping in odd-sized matrices, thus the spiral order is obtained in O(m*n) time.
9. Print First N Fibonacci Numbers
Problem Statement
In financial modeling for compound interest projections, generate the first N Fibonacci numbers to simulate growth patterns in a sequence.
Sample Input
10
Sample Output
0 1 1 2 3 5 8 13 21 34
Solutions
C
#include <stdio.h>
void printFibonacci(int n) {
int a = 0, b = 1, c;
for (int i = 0; i < n; i++) {
printf("%d ", a);
c = a + b;
a = b;
b = c;
}
}
int main() {
int n;
scanf("%d", &n);
printFibonacci(n);
printf("\n");
return 0;
}C++
#include <iostream>
using namespace std;
void printFibonacci(int n) {
int a = 0, b = 1, c;
for (int i = 0; i < n; i++) {
cout << a << " ";
c = a + b;
a = b;
b = c;
}
}
int main() {
int n;
cin >> n;
printFibonacci(n);
cout << endl;
return 0;
}Java
import java.util.Scanner;
public class Fibonacci {
public static void printFibonacci(int n) {
int a = 0, b = 1, c;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
c = a + b;
a = b;
b = c;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
printFibonacci(n);
System.out.println();
scanner.close();
}
}Python
def print_fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
n = int(input())
print_fibonacci(n)
print()
Explanation of Code
Starts with 0 and 1, each subsequent number is the sum of the previous two, printed iteratively. Efficient O(n) space and time, avoiding recursion depth issues.
10. Find the First Non-Repeating Character from a Stream of Characters
Problem Statement
In log analysis for error detection, process a stream of characters (string) to find the first unique character that doesn't repeat, indicating a rare event.
Sample Input
swiss
Sample Output
First non-repeating character: w
Solutions
C
#include <stdio.h>
#include <string.h>
char firstNonRepeating(char *str) {
int count[256] = {0};
for (int i = 0; str[i]; i++) {
count[str[i]]++;
}
for (int i = 0; str[i]; i++) {
if (count[str[i]] == 1) {
return str[i];
}
}
return '\0';
}
int main() {
char str[100];
scanf("%s", str);
char result = firstNonRepeating(str);
if (result) {
printf("First non-repeating character: %c\n", result);
} else {
printf("No non-repeating character found.\n");
}
return 0;
}C++
#include <iostream>
#include <unordered_map>
using namespace std;
char firstNonRepeating(string str) {
unordered_map<char, int> count;
for (char c : str) {
count[c]++;
}
for (char c : str) {
if (count[c] == 1) {
return c;
}
}
return '\0';
}
int main() {
string str;
cin >> str;
char result = firstNonRepeating(str);
if (result != '\0') {
cout << "First non-repeating character: " << result << endl;
} else {
cout << "No non-repeating character found." << endl;
}
return 0;
}Java
import java.util.HashMap;
import java.util.Scanner;
public class FirstNonRepeating {
public static char firstNonRepeating(String str) {
HashMap<Character, Integer> countMap = new HashMap<>();
for (char c : str.toCharArray()) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
for (char c : str.toCharArray()) {
if (countMap.get(c) == 1) {
return c;
}
}
return '\0';
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
char result = firstNonRepeating(str);
if (result != '\0') {
System.out.println("First non-repeating character: " + result);
} else {
System.out.println("No non-repeating character found.");
}
scanner.close();
}
}Python
def first_non_repeating(s):
count = {}
for char in s:
count[char] = count.get(char, 0) + 1
for char in s:
if count[char] == 1:
return char
return None
s = input()
result = first_non_repeating(s)
if result:
print("First non-repeating character:", result)
else:
print("No non-repeating character found.")Explanation of Code
Counts frequency with a map/array, then scans again to find the first with count 1. O(n) time, O(1) space for fixed charset.
11. Remove Duplicates from Sorted Array
Problem Statement
In data cleanup for a sorted list of user IDs, remove duplicates in-place to maintain a unique sequence for database deduplication.
Sample Input
0 0 1 1 2 2 3 4
Sample Output
0 1 2 3 4
Solutions
C
#include <stdio.h>
int removeDuplicates(int arr[], int n) {
if (n == 0) return 0;
int j = 0;
for (int i = 1; i < n; i++) {
if (arr[i] != arr[j]) {
j++;
arr[j] = arr[i];
}
}
return j + 1;
}
int main() {
int n = 8;
int arr[8];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int new_n = removeDuplicates(arr, n);
for (int i = 0; i < new_n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}C++
#include <iostream>
#include <vector>
using namespace std;
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int j = 0;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] != nums[j]) {
j++;
nums[j] = nums[i];
}
}
return j + 1;
}
int main() {
vector<int> nums(8);
for (int i = 0; i < 8; i++) {
cin >> nums[i];
}
int new_n = removeDuplicates(nums);
for (int i = 0; i < new_n; i++) {
cout << nums[i] << " ";
}
cout << endl;
return 0;
}Java
import java.util.Scanner;
public class RemoveDuplicates {
public static int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int j = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[j]) {
j++;
nums[j] = nums[i];
}
}
return j + 1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] nums = new int[8];
for (int i = 0; i < 8; i++) {
nums[i] = scanner.nextInt();
}
int n = removeDuplicates(nums);
for (int i = 0; i < n; i++) {
System.out.print(nums[i] + " ");
}
System.out.println();
scanner.close();
}
}Python
def remove_duplicates(nums):
if not nums:
return 0
j = 0
for i in range(1, len(nums)):
if nums[i] != nums[j]:
j += 1
nums[j] = nums[i]
return j + 1
nums = list(map(int, input().split()))
n = remove_duplicates(nums)
print(' '.join(map(str, nums[:n])))
Explanation of Code
Uses two pointers: one tracks unique position (j), advances and overwrites when new value found. Leverages sorted order for O(n) efficiency.
12. Check if a Number is Palindrome
Problem Statement
In a banking system, verify if a transaction ID (read as a number) reads the same forwards and backwards to detect data entry errors during reconciliation.
Sample Input
12321
Sample Output
Yes
Solutions
C
#include <stdio.h>
int isPalindrome(int num) {
int original = num, reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return original == reversed;
}
int main() {
int n;
scanf("%d", &n);
if (isPalindrome(n)) {
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}C++
#include <iostream>
using namespace std;
bool isPalindrome(int num) {
int original = num, reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return original == reversed;
}
int main() {
int n;
cin >> n;
if (isPalindrome(n)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}Java
import java.util.Scanner;
public class PalindromeNumber {
public static boolean isPalindrome(int num) {
int original = num, reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return original == reversed;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if (isPalindrome(n)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
scanner.close();
}
}Python
def is_palindrome(num):
original = num
reversed_num = 0
while num > 0:
reversed_num = reversed_num * 10 + num % 10
num //= 10
return original == reversed_num
n = int(input())
if is_palindrome(n):
print("Yes")
else:
print("No")Explanation of Code
The code reverses the number by extracting digits via modulo and division, then compares to the original. Handles positive integers in O(log n) time; assumes no leading zeros.
13. Find Factorial of a Number
Problem Statement
In a combinatorics calculator for scheduling shifts, compute the factorial of employee count to determine possible arrangements without repetition.
Sample Input
5
Sample Output
120
Solutions
C
#include <stdio.h>
long long factorial(int n) {
if (n == 0) return 1;
long long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
int main() {
int n;
scanf("%d", &n);
printf("%lld\n", factorial(n));
return 0;
}C++
#include <iostream>
using namespace std;
long long factorial(int n) {
if (n == 0) return 1;
long long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
int main() {
int n;
cin >> n;
cout << factorial(n) << endl;
return 0;
}Java
import java.util.Scanner;
public class Factorial {
public static long factorial(int n) {
if (n == 0) return 1;
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(factorial(n));
scanner.close();
}
}Python
def factorial(n):
if n == 0:
return 1
fact = 1
for i in range(1, n + 1):
fact *= i
return fact
n = int(input())
print(factorial(n))Explanation of Code
Iteratively multiplies numbers from 1 to n, handling base case 0! = 1. Uses long long in C/C++ for larger values; time O(n), may overflow for big n.
14. Check if a Number is Prime
Problem Statement
In cryptography key generation, check if a candidate number is prime to ensure secure prime factors for encryption algorithms.
Sample Input
17
Sample Output
Yes
Solutions
C
#include <stdio.h>
#include <math.h>
int isPrime(int n) {
if (n <= 1) return 0;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return 0;
}
return 1;
}
int main() {
int n;
scanf("%d", &n);
if (isPrime(n)) {
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}C++
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
int n;
cin >> n;
if (isPrime(n)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}Java
import java.util.Scanner;
public class PrimeCheck {
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if (isPrime(n)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
scanner.close();
}
}Python
import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
n = int(input())
if is_prime(n):
print("Yes")
else:
print("No")Explanation of Code
Checks divisibility up to sqrt(n) for efficiency. Returns Yes/No based on no divisors found other than 1 and itself. Time O(sqrt(n)).
15. Reverse a String
Problem Statement
In text processing for a chat app, reverse user messages to create a fun "mirror" effect before sending to recipients.
Sample Input
hello
Sample Output
olleh
Solutions
C
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
int main() {
char str[100];
scanf("%s", str);
reverseString(str);
printf("%s\n", str);
return 0;
}C++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
cin >> str;
reverse(str.begin(), str.end());
cout << str << endl;
return 0;
}Java
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
StringBuilder reversed = new StringBuilder(str).reverse();
System.out.println(reversed);
scanner.close();
}
}Python
s = input()
reversed_s = s[::-1]
print(reversed_s)Explanation of Code
Swaps characters from ends moving inward (C), or uses built-in reverse (others). O(n) time, in-place for C.
16. Find Largest Element in an Array
Problem Statement
In sensor data monitoring, identify the maximum reading from an array of temperature values to trigger alerts if above threshold.
Sample Input
5
10 20 15 30 25
Sample Output
30
Solutions
C
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int arr[100];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) max = arr[i];
}
printf("%d\n", max);
return 0;
}C++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
int arr[100];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int max_val = *max_element(arr, arr + n);
cout << max_val << endl;
return 0;
}Java
import java.util.Scanner;
public class LargestElement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) max = arr[i];
}
System.out.println(max);
scanner.close();
}
}Python
n = int(input())
arr = list(map(int, input().split()))
print(max(arr))Explanation of Code
Iterates through array tracking max value, or uses built-in max. O(n) time.
17. Count Vowels in a String
Problem Statement
In a sentiment analysis tool, count vowels in customer feedback text to gauge emotional tone based on vowel frequency.
Sample Input
hello
Sample Output
2
Solutions
C
#include <stdio.h>
#include <string.h>
int countVowels(char str[]) {
int count = 0;
for (int i = 0; str[i]; i++) {
char c = tolower(str[i]);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') count++;
}
return count;
}
int main() {
char str[100];
scanf("%s", str);
printf("%d\n", countVowels(str));
return 0;
}C++
#include <iostream>
#include <string>
using namespace std;
int countVowels(string str) {
int count = 0;
for (char c : str) {
c = tolower(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') count++;
}
return count;
}
int main() {
string str;
cin >> str;
cout << countVowels(str) << endl;
return 0;
}Java
import java.util.Scanner;
public class CountVowels {
public static int countVowels(String str) {
int count = 0;
str = str.toLowerCase();
for (char c : str.toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') count++;
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
System.out.println(countVowels(str));
scanner.close();
}
}Python
s = input().lower()
vowels = 'aeiou'
count = sum(1 for char in s if char in vowels)
print(count)Explanation of Code
Converts to lowercase, counts occurrences of a/e/i/o/u. O(n) time.
18. Linear Search in Array
Problem Statement
In inventory lookup, search for a product ID in a list of stocked items to check availability.
Sample Input
5
10 20 30 40 50
30
Sample Output
Found at index 2
Solutions
C
#include <stdio.h>
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) return i;
}
return -1;
}
int main() {
int n;
scanf("%d", &n);
int arr[100];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int key;
scanf("%d", &key);
int index = linearSearch(arr, n, key);
if (index != -1) {
printf("Found at index %d\n", index);
} else {
printf("Not found\n");
}
return 0;
}C++
#include <iostream>
using namespace std;
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) return i;
}
return -1;
}
int main() {
int n;
cin >> n;
int arr[100];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cin >> key;
int index = linearSearch(arr, n, key);
if (index != -1) {
cout << "Found at index " << index << endl;
} else {
cout << "Not found" << endl;
}
return 0;
}Java
import java.util.Scanner;
public class LinearSearch {
public static int linearSearch(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) return i;
}
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int key = scanner.nextInt();
int index = linearSearch(arr, key);
if (index != -1) {
System.out.println("Found at index " + index);
} else {
System.out.println("Not found");
}
scanner.close();
}
}Python
n = int(input())
arr = list(map(int, input().split()))
key = int(input())
index = -1
for i in range(n):
if arr[i] == key:
index = i
break
if index != -1:
print(f"Found at index {index}")
else:
print("Not found")Explanation of Code
Scans array sequentially until key matches, returns index or -1. O(n) time worst case.
19. Bubble Sort on Array
Problem Statement
In report generation, sort employee performance scores in ascending order using simple swaps for small datasets.
Sample Input
5
64 34 25 12 22
Sample Output
12 22 25 34 64
Solutions
C
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int n;
scanf("%d", &n);
int arr[100];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
bubbleSort(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}C++
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
int n;
cin >> n;
int arr[100];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
bubbleSort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}Java
import java.util.Scanner;
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
bubbleSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
scanner.close();
}
}Python
n = int(input())
arr = list(map(int, input().split()))
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
print(' '.join(map(str, arr)))Explanation of Code
Repeatedly swaps adjacent elements if out of order, bubbling largest to end each pass. O(n^2) time.
20. Armstrong Number Check
Problem Statement
In a puzzle game app, check if a player's score is an Armstrong number (sum of cubes of digits equals itself) to award bonus points.
Sample Input
153
Sample Output
Yes
Solutions
C
#include <stdio.h>
#include <math.h>
int isArmstrong(int num) {
int original = num, sum = 0, digits = 0;
int temp = num;
while (temp > 0) {
digits++;
temp /= 10;
}
temp = num;
while (temp > 0) {
sum += pow(temp % 10, digits);
temp /= 10;
}
return sum == original;
}
int main() {
int n;
scanf("%d", &n);
if (isArmstrong(n)) {
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}C++
#include <iostream>
#include <cmath>
using namespace std;
bool isArmstrong(int num) {
int original = num, sum = 0, digits = 0;
int temp = num;
while (temp > 0) {
digits++;
temp /= 10;
}
temp = num;
while (temp > 0) {
sum += pow(temp % 10, digits);
temp /= 10;
}
return sum == original;
}
int main() {
int n;
cin >> n;
if (isArmstrong(n)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}Java
import java.util.Scanner;
public class ArmstrongCheck {
public static boolean isArmstrong(int num) {
int original = num, sum = 0, digits = 0;
int temp = num;
while (temp > 0) {
digits++;
temp /= 10;
}
temp = num;
while (temp > 0) {
sum += Math.pow(temp % 10, digits);
temp /= 10;
}
return sum == original;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if (isArmstrong(n)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
scanner.close();
}
}Python
import math
def is_armstrong(num):
original = num
digits = len(str(num))
sum_val = 0
while num > 0:
sum_val += math.pow(num % 10, digits)
num //= 10
return sum_val == original
n = int(input())
if is_armstrong(n):
print("Yes")
else:
print("No")Explanation of Code
Counts digits, sums each digit raised to digit count power, compares to original. O(log n) time.
Programming Languages and Code Implementation
The programming language that you use can make a big difference in your performance when you are getting ready for coding interviews or taking part in competitive programming challenges. Various companies and platforms accept different languages, and it is necessary that you know some of the most frequently used ones. Here we will examine the programming languages that are typically the case in coding interviews, particularly for companies like Infosys, and talk about how these languages can be used to solve problems in data structures and algorithms (DSA), DBMS, etc.
C and C++
C and C++ are foundational languages that have been staples in competitive coding and algorithm-based challenges for years. They are known for their high performance, efficient memory management, and flexibility.
- C: Great for low-level programming and control over system resources. In competitive coding, C is often chosen for its simplicity and fast execution. Problems involving data structures like arrays, linked lists, or trees can be solved effectively in C.
- C++: This language builds on C and adds features such as object-oriented programming (OOP), STL (Standard Template Library), and automatic memory management. In competitive coding, C++ is widely used due to its built-in data structures like vectors, sets, and maps, which simplify many coding problems. It's also one of the most common languages for solving DSA problems in coding interviews.
Java
Java is a highly popular programming language in both enterprise-level applications and coding interviews. Known for its portability and ease of use, Java is commonly used in companies like Infosys for coding interviews.
Java’s built-in libraries like ArrayList, HashMap, and LinkedList provide efficient solutions for data manipulation. Its object-oriented nature allows for modular code, and it offers automatic garbage collection, making memory management easier for developers. In coding interviews, problems involving object-oriented programming (OOP) concepts, inheritance, and polymorphism can be solved effectively using Java.
Python
Python has become very popular mainly because of its simplicity and user-friendliness, hence it is a perfect language for competitive coding and interview problems. With Python being less confusing, developers can concentrate more on problem-solving than the language syntax. It is particularly great for coding up data structure and algorithm problems fast.
Python also has strong support for data manipulation libraries, like NumPy and Pandas, and has built-in functions for sorting, searching, and other common tasks. It’s widely used in coding rounds, especially for problems that involve graphs, dynamic programming (DP), or greedy algorithms.
SQL
In many coding interviews, especially those focusing on DBMS (Database Management Systems), candidates are expected to demonstrate their SQL skills. SQL is used to query, update, and manage relational databases. In coding problems, you may be asked to perform tasks such as retrieving subsets of data, joining tables, or filtering information based on certain conditions.
Competitive Coding and DSA
For competitive coding, it is usually expected that candidates are highly skilled in C, C++, Java, and Python. These languages are typically employed in the resolution of DSA (Data Structures and Algorithms) problems, examples of which are sorting algorithms, graph traversal and searching algorithms. It is very important to know the time and space complexities of the algorithms and also how to implement them efficiently in these languages.
Sample Coding Questions with Solutions
Practice is essential for cracking coding interviews. Below, we provide a couple of representative coding questions often asked in coding rounds, along with solutions to help you understand the expected approach and reasoning.
Problem 1: Subset Sum Problem
Problem Statement:
Given a set of non-negative integers and a target sum, determine if there is a subset of the given set whose sum is equal to the target sum.
- Input: A set of integers (e.g., {3, 34, 4, 12, 5, 2}) and a target sum (e.g., 9).
- Output: True if there is a subset whose sum equals the target, otherwise False.
Solution:
This problem can be solved using dynamic programming (DP). We maintain a 2D DP table where each entry dp[i][j] represents whether there is a subset of the first i elements of the set that sums to j. If we find dp[n][target] to be True, we know that a subset exists.
def subset_sum(nums, target):
dp = [False] * (target + 1) # Initialize DP array of size (target + 1), all set to False.
dp[0] = True # Base case: A sum of 0 is always achievable with an empty subset.
for num in nums: # Iterate over all numbers in the input list `nums`.
for i in range(target, num - 1, -1): # Iterate backwards from target to num (to prevent reuse of same element in this iteration).
dp[i] = dp[i] or dp[i - num] # If dp[i - num] is True, then dp[i] becomes True.
return dp[target] # Return True if dp[target] is True (indicating a subset with the given target sum exists).
# Example usage:
nums = [3, 34, 4, 12, 5, 2] # List of numbers.
target = 9 # The target sum we're looking for.
print(subset_sum(nums, target)) # Output: TrueProblem 2: Coding Round Example - Find the Subset
Problem Statement:
Given a given set of non-negative integers and a target sum, print all the subsets that sum up to the target sum.
Solution Approach:
We use a recursive approach to generate all subsets and check their sum. This will give us all possible subsets, and we will check if their sum matches the target.
def find_subsets(nums, target):
result = [] # This will store the final result (list of valid subsets).
def backtrack(start, path, target):
# Base case: if the remaining target is 0, we've found a valid subset
if target == 0:
result.append(path)
return
for i in range(start, len(nums)): # Iterate over the elements starting from 'start'
if nums[i] > target: # If the current element exceeds the target, skip it
continue
# Include the current element in the subset and reduce the target accordingly
backtrack(i + 1, path + [nums[i]], target - nums[i]) # Move to the next element
# Start the backtracking process from index 0, an empty path, and the given target
backtrack(0, [], target)
return result # Return the list of valid subsets
# Example usage:
nums = [3, 34, 4, 12, 5, 2] # List of numbers
target = 9 # The target sum
print(find_subsets(nums, target)) # Output: [[4, 5], [3, 4, 2]]This solution uses backtracking to explore all subsets and keep track of the ones that match the target sum.


.avif)






