// Factor of a number
public class Factors {
public static void main(String[] args) {
int num = 28;
System.out.print("Factors: ");
for (int i = 1; i <= num; i++) {
if (num % i == 0) System.out.print(i + " ");
// Prime Factors
public class PrimeFactors {
public static void main(String[] args) {
int num = 28;
System.out.print("Prime Factors: ");
for (int i = 2; i <= num; i++) {
while (num % i == 0) {
System.out.print(i + " ");
num /= i;
// Strong Number
public class StrongNumber {
public static void main(String[] args) {
int num = 145, temp = num, sum = 0;
while (temp > 0) {
int digit = temp % 10, fact = 1;
for (int i = 1; i <= digit; i++) fact *= i;
sum += fact;
temp /= 10;
System.out.println("Strong Number: " + (sum == num));
// Perfect Number
public class PerfectNumber {
public static void main(String[] args) {
int num = 28, sum = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0) sum += i;
System.out.println("Perfect Number: " + (sum == num));
// Perfect Square
public class PerfectSquare {
public static void main(String[] args) {
int num = 49;
int sqrt = (int)Math.sqrt(num);
System.out.println("Perfect Square: " + (sqrt * sqrt == num));
// Automorphic Number
public class AutomorphicNumber {
public static void main(String[] args) {
int num = 76;
int square = num * num;
String numStr = String.valueOf(num);
String squareStr = String.valueOf(square);
System.out.println("Automorphic: " + squareStr.endsWith(numStr));
// Harshad Number
public class HarshadNumber {
public static void main(String[] args) {
int num = 156, sum = 0, temp = num;
while (temp > 0) {
sum += temp % 10;
temp /= 10;
System.out.println("Harshad Number: " + (num % sum == 0));
// Abundant Number
public class AbundantNumber {
public static void main(String[] args) {
int num = 18, sum = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0) sum += i;
System.out.println("Abundant Number: " + (sum > num));
}
// Friendly Pair
public class FriendlyPair {
public static int sumOfDivisors(int n) {
int sum = 0;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) sum += i;
return sum;
public static void main(String[] args) {
int a = 6, b = 28;
float ratio1 = (float)sumOfDivisors(a) / a;
float ratio2 = (float)sumOfDivisors(b) / b;
System.out.println("Friendly Pair: " + (ratio1 == ratio2));
// Positive or Negative
public class PositiveNegative {
public static void main(String[] args) {
int num = -5;
if (num > 0) System.out.println("Positive");
else if (num < 0) System.out.println("Negative");
else System.out.println("Zero");
// Even or Odd
public class EvenOdd {
public static void main(String[] args) {
int num = 10;
System.out.println(num % 2 == 0 ? "Even" : "Odd");
// Sum of First N Natural Numbers (formula)
public class SumFirstNNumbers {
public static void main(String[] args) {
int n = 10;
int sum = n * (n + 1) / 2;
System.out.println("Sum: " + sum);
// Sum of N natural numbers (loop)
public class SumNNumbers {
public static void main(String[] args) {
int n = 10, sum = 0;
for (int i = 1; i <= n; i++) sum += i;
System.out.println("Sum: " + sum);
// Sum of numbers in range
public class SumInRange {
public static void main(String[] args) {
int start = 5, end = 10, sum = 0;
for (int i = start; i <= end; i++) sum += i;
System.out.println("Sum: " + sum);
}
// Greatest of two numbers
public class GreatestOfTwo {
public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("Greatest: " + (a > b ? a : b));
// Greatest of three numbers
public class GreatestOfThree {
public static void main(String[] args) {
int a = 10, b = 30, c = 20;
System.out.println("Greatest: " + (a > b ? (a > c ? a : c) : (b > c ? b : c)));
// Leap year
public class LeapYear {
public static void main(String[] args) {
int year = 2024;
boolean isLeap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
System.out.println("Leap Year: " + isLeap);
// Prime number
public class PrimeCheck {
public static void main(String[] args) {
int num = 29;
boolean isPrime = true;
if (num <= 1) isPrime = false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) isPrime = false;
System.out.println("Prime: " + isPrime);
// Prime numbers in range
public class PrimeInRange {
public static void main(String[] args) {
int start = 10, end = 50;
for (int num = start; num <= end; num++) {
boolean isPrime = true;
if (num <= 1) continue;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
if (isPrime) System.out.print(num + " ");
// Sum of digits
public class SumOfDigits {
public static void main(String[] args) {
int num = 1234, sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
System.out.println("Sum of digits: " + sum);
// Reverse of a number
public class ReverseNumber {
public static void main(String[] args) {
int num = 1234, rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
System.out.println("Reverse: " + rev);
// Palindrome number
public class PalindromeCheck {
public static void main(String[] args) {
int num = 121, original = num, rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
System.out.println("Palindrome: " + (original == rev));
}
// Armstrong number
public class ArmstrongCheck {
public static void main(String[] args) {
int num = 153, original = num, sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
System.out.println("Armstrong: " + (original == sum));
// Armstrong numbers in range
public class ArmstrongInRange {
public static void main(String[] args) {
for (int num = 100; num <= 999; num++) {
int original = num, sum = 0, temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
if (sum == original) System.out.print(original + " ");
// Fibonacci series up to n terms
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10, a = 0, b = 1;
System.out.print("Fibonacci: ");
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
// Nth term of Fibonacci series
public class NthFibonacci {
public static int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
public static void main(String[] args) {
int n = 6;
System.out.println("Nth Fibonacci: " + fib(n));
// Factorial of a number
public class Factorial {
public static void main(String[] args) {
int n = 5, fact = 1;
for (int i = 2; i <= n; i++) fact *= i;
System.out.println("Factorial: " + fact);
}
// Power of a number
public class PowerCalc {
public static void main(String[] args) {
int base = 2, exp = 3, result = 1;
for (int i = 1; i <= exp; i++) result *= base;
System.out.println("Power: " + result);
// LCM of two numbers
public class LCM {
public static void main(String[] args) {
int a = 12, b = 18;
int max = Math.max(a, b);
int lcm = max;
while (true) {
if (lcm % a == 0 && lcm % b == 0) break;
lcm++;
System.out.println("LCM: " + lcm);
// HCF of two numbers
public class HCF {
public static void main(String[] args) {
int a = 12, b = 18;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
System.out.println("HCF: " + a);
// Greatest Common Divisor
public class GCD {
public static void main(String[] args) {
int a = 36, b = 60;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
System.out.println("GCD: " + a);
// Binary to Decimal
public class BinaryToDecimal {
public static void main(String[] args) {
String binary = "1010";
int decimal = Integer.parseInt(binary, 2);
System.out.println("Decimal: " + decimal);
// Octal to Decimal
public class OctalToDecimal {
public static void main(String[] args) {
String octal = "17";
int decimal = Integer.parseInt(octal, 8);
System.out.println("Decimal: " + decimal);
// Hexadecimal to Decimal
public class HexToDecimal {
public static void main(String[] args) {
String hex = "1A";
int decimal = Integer.parseInt(hex, 16);
System.out.println("Decimal: " + decimal);
// Decimal to Binary
public class DecimalToBinary {
public static void main(String[] args) {
int num = 10;
System.out.println("Binary: " + Integer.toBinaryString(num));
// Decimal to Octal
public class DecimalToOctal {
public static void main(String[] args) {
int num = 15;
System.out.println("Octal: " + Integer.toOctalString(num));
// Decimal to Hexadecimal
public class DecimalToHex {
public static void main(String[] args) {
int num = 26;
System.out.println("Hexadecimal: " + Integer.toHexString(num));
// Binary to Octal
public class BinaryToOctal {
public static void main(String[] args) {
String binary = "1010";
int decimal = Integer.parseInt(binary, 2);
System.out.println("Octal: " + Integer.toOctalString(decimal));
// Octal to Binary
public class OctalToBinary {
public static void main(String[] args) {
String octal = "12";
int decimal = Integer.parseInt(octal, 8);
System.out.println("Binary: " + Integer.toBinaryString(decimal));
// Coordinate Quadrant
public class Quadrant {
public static void main(String[] args) {
int x = -3, y = 4;
if (x > 0 && y > 0) System.out.println("Quadrant I");
else if (x < 0 && y > 0) System.out.println("Quadrant II");
else if (x < 0 && y < 0) System.out.println("Quadrant III");
else if (x > 0 && y < 0) System.out.println("Quadrant IV");
else System.out.println("Lies on Axis");
// Permutations (nPr)
public class Permutations {
public static int factorial(int n) {
int f = 1;
for (int i = 2; i <= n; i++) f *= i;
return f;
public static void main(String[] args) {
int n = 5, r = 2;
int nPr = factorial(n) / factorial(n - r);
System.out.println("Permutations: " + nPr);
// Maximum handshakes
public class Handshakes {
public static void main(String[] args) {
int n = 5;
int handshakes = n * (n - 1) / 2;
System.out.println("Max Handshakes: " + handshakes);
// Addition of two fractions
public class FractionAddition {
public static void main(String[] args) {
int num1 = 1, den1 = 2;
int num2 = 1, den2 = 3;
int lcm = den1 * den2;
int numerator = num1 * (lcm / den1) + num2 * (lcm / den2);
System.out.println("Sum: " + numerator + "/" + lcm);
// Replace 0s with 1s
public class ReplaceZeros {
public static void main(String[] args) {
int num = 1020, result = 0, place = 1;
while (num > 0) {
int digit = num % 10;
if (digit == 0) digit = 1;
result += digit * place;
num /= 10;
place *= 10;
System.out.println("Modified: " + result);
// Sum of two prime numbers
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 void main(String[] args) {
int num = 34;
boolean canBe = false;
for (int i = 2; i <= num / 2; i++) {
if (isPrime(i) && isPrime(num - i)) {
System.out.println(num + " = " + i + " + " + (num - i));
canBe = true;
break;
if (!canBe) System.out.println("Cannot be expressed as sum of two primes");
// Area of Circle
public class AreaOfCircle {
public static void main(String[] args) {
double radius = 5;
double area = Math.PI * radius * radius;
System.out.println("Area: " + area);
// Prime numbers 1 to 100
public class Prime1To100 {
public static void main(String[] args) {
for (int i = 2; i <= 100; i++) {
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
isPrime = false;
break;
if (isPrime) System.out.print(i + " ");
// Count digits
public class CountDigits {
public static void main(String[] args) {
int num = 12345, count = 0;
while (num > 0) {
count++;
num /= 10;
System.out.println("Digits: " + count);
// Number to Words (0-999 only)
public class NumberToWords {
static final String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen"};
static final String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty",
"Ninety"};
public static void main(String[] args) {
int num = 123;
if (num == 0) System.out.println("Zero");
else {
String words = "";
if (num >= 100) {
words += ones[num / 100] + " Hundred ";
num %= 100;
if (num >= 20) {
words += tens[num / 10] + " ";
num %= 10;
words += ones[num];
System.out.println(words.trim());
// Days in a month
public class DaysInMonth {
public static void main(String[] args) {
int month = 2, year = 2024;
int days;
switch (month) {
case 2:
days = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
default:
days = 31;
System.out.println("Days: " + days);
}
// Count x digit in number
public class CountDigitX {
public static void main(String[] args) {
int num = 122232, x = 2, count = 0;
while (num > 0) {
if (num % 10 == x) count++;
num /= 10;
System.out.println("Count of " + x + ": " + count);
// Integers with exactly x divisors (brute force)
public class XDivisors {
public static void main(String[] args) {
int x = 6, limit = 100;
for (int num = 1; num <= limit; num++) {
int count = 0;
for (int i = 1; i <= num; i++) if (num % i == 0) count++;
if (count == x) System.out.print(num + " ");
// Roots of quadratic equation
public class QuadraticRoots {
public static void main(String[] args) {
double a = 1, b = -3, c = 2;
double d = b * b - 4 * a * c;
if (d > 0) {
double r1 = (-b + Math.sqrt(d)) / (2 * a);
double r2 = (-b - Math.sqrt(d)) / (2 * a);
System.out.println("Roots: " + r1 + ", " + r2);
} else if (d == 0) {
double r = -b / (2 * a);
System.out.println("One root: " + r);
} else {
System.out.println("Imaginary Roots");
// Power of a Number using Recursion
public class PowerRecursion {
static int power(int base, int exp) {
if (exp == 0) return 1;
return base * power(base, exp - 1);
public static void main(String[] args) {
System.out.println(power(2, 5));
// Prime Number using Recursion
public class PrimeRecursion {
static boolean isPrime(int num, int i) {
if (num <= 2) return num == 2;
if (num % i == 0) return false;
if (i * i > num) return true;
return isPrime(num, i + 1);
}
public static void main(String[] args) {
System.out.println(isPrime(29, 2));
// Largest element in array using recursion
public class MaxInArray {
static int findMax(int[] arr, int n) {
if (n == 1) return arr[0];
return Math.max(arr[n - 1], findMax(arr, n - 1));
public static void main(String[] args) {
int[] arr = {1, 4, 45, 6, -50};
System.out.println(findMax(arr, arr.length));
// Smallest element in array using recursion
public class MinInArray {
static int findMin(int[] arr, int n) {
if (n == 1) return arr[0];
return Math.min(arr[n - 1], findMin(arr, n - 1));
public static void main(String[] args) {
int[] arr = {1, 4, 45, 6, -50};
System.out.println(findMin(arr, arr.length));
// Reverse a number using recursion
public class ReverseNumberRec {
static int reverse(int num, int rev) {
if (num == 0) return rev;
return reverse(num / 10, rev * 10 + num % 10);
public static void main(String[] args) {
System.out.println(reverse(1234, 0));
// HCF using Recursion
public class HCFRecursion {
static int hcf(int a, int b) {
if (b == 0) return a;
return hcf(b, a % b);
public static void main(String[] args) {
System.out.println(hcf(48, 18));
// LCM using HCF
public class LCMRecursion {
static int hcf(int a, int b) {
if (b == 0) return a;
return hcf(b, a % b);
static int lcm(int a, int b) {
return (a * b) / hcf(a, b);
public static void main(String[] args) {
System.out.println(lcm(12, 18));
// String length using recursion
public class StringLengthRec {
static int length(String str) {
if (str.equals("")) return 0;
return 1 + length(str.substring(1));
public static void main(String[] args) {
System.out.println(length("Hello"));
// All Permutations of a String
public class Permutations {
static void permute(String str, String ans) {
if (str.length() == 0) {
System.out.println(ans);
return;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
String ros = str.substring(0, i) + str.substring(i + 1);
permute(ros, ans + ch);
public static void main(String[] args) {
permute("ABC", "");
}
}
// Nth Fibonacci Term using recursion
public class FibonacciNthRec {
static int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
public static void main(String[] args) {
System.out.println(fib(7));
// Subset sum of array
public class SubsetSums {
static void subsetSums(int[] arr, int n, int index, int sum) {
if (index == n) {
System.out.print(sum + " ");
return;
subsetSums(arr, n, index + 1, sum + arr[index]);
subsetSums(arr, n, index + 1, sum);
public static void main(String[] args) {
int[] arr = {2, 3};
subsetSums(arr, arr.length, 0, 0);
// Last non-zero digit in factorial (placeholder for simplicity)
public class LastNonZeroDigit {
public static void main(String[] args) {
int n = 5;
int fact = 1;
for (int i = 2; i <= n; i++) fact *= i;
while (fact % 10 == 0) fact /= 10;
System.out.println(fact % 10);
// Nth row of Pascal's Triangle
public class PascalsTriangleRow {
static int comb(int n, int k) {
if (k == 0 || k == n) return 1;
return comb(n - 1, k - 1) + comb(n - 1, k);
public static void main(String[] args) {
int n = 4;
for (int i = 0; i <= n; i++) System.out.print(comb(n, i) + " ");
// Generate balanced parentheses
public class BalancedParentheses {
static void generate(int open, int close, String str) {
if (open == 0 && close == 0) {
System.out.println(str);
return;
if (open > 0) generate(open - 1, close, str + "(");
if (close > open) generate(open, close - 1, str + ")");
}
public static void main(String[] args) {
int n = 3;
generate(n, n, "");
// Factorial using recursion
public class FactorialRec {
static int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
public static void main(String[] args) {
System.out.println(fact(5));
// Palindromic partitions (basic)
public class PalindromicPartitions {
static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i++) != str.charAt(j--)) return false;
return true;
static void partition(String s, String out) {
if (s.length() == 0) {
System.out.println(out);
return;
}
for (int i = 1; i <= s.length(); i++) {
String prefix = s.substring(0, i);
if (isPalindrome(prefix)) {
partition(s.substring(i), out + prefix + " ");
public static void main(String[] args) {
partition("aab", "");
// N-bit binary numbers with more or equal 1’s than 0’s
public class NBitBinary {
static void generate(int ones, int zeros, int n, String out) {
if (n == 0) {
System.out.println(out);
return;
generate(ones + 1, zeros, n - 1, out + "1");
if (ones > zeros) generate(ones, zeros + 1, n - 1, out + "0");
public static void main(String[] args) {
generate(0, 0, 3, "");
// All subsets
public class AllSubsets {
static void subsets(String str, String ans) {
if (str.equals("")) {
System.out.println(ans);
return;
subsets(str.substring(1), ans);
subsets(str.substring(1), ans + str.charAt(0));
public static void main(String[] args) {
subsets("abc", "");
// Remove adjacent duplicates recursively
public class RemoveAdjDuplicates {
static String remove(String str) {
if (str.length() <= 1) return str;
if (str.charAt(0) == str.charAt(1)) return remove(str.substring(1));
return str.charAt(0) + remove(str.substring(1));
public static void main(String[] args) {
System.out.println(remove("aabbccdde"));
// Java code for each important beginner-level array and string problem
// 1. Largest Element in Array
public class LargestElement {
public static void main(String[] args) {
int[] arr = {10, 50, 20, 90, 30};
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
System.out.println("Largest: " + max);
// 2. Second Largest Element
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : arr) {
if (n > max) {
second = max;
max = n;
} else if (n > second && n != max) {
second = n;
System.out.println("Second Largest: " + second);
// 3. Check if Array is Sorted
public class IsSorted {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
boolean sorted = true;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
sorted = false;
break;
}
System.out.println("Sorted: " + sorted);
// 4. Reverse an Array
public class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int left = 0, right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
for (int n : arr) System.out.print(n + " ");
// 5. Missing Number (1 to N)
public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5};
int n = 5; // supposed to be from 1 to 5
int total = n * (n + 1) / 2;
int sum = 0;
for (int num : arr) sum += num;
System.out.println("Missing Number: " + (total - sum));
}
// 6. Duplicate Element
public class FindDuplicate {
public static void main(String[] args) {
int[] arr = {1, 3, 4, 2, 2};
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
System.out.println("Duplicate: " + arr[i]);
return;
// 7. Count Frequency of Each Element
import java.util.HashMap;
public class FrequencyCount {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 3, 3};
HashMap<Integer, Integer> freq = new HashMap<>();
for (int num : arr) freq.put(num, freq.getOrDefault(num, 0) + 1);
System.out.println(freq);
// 8. Move All Zeros to End
public class MoveZeros {
public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
int index = 0;
for (int num : arr) {
if (num != 0) arr[index++] = num;
while (index < arr.length) arr[index++] = 0;
for (int n : arr) System.out.print(n + " ");
// 9. Left Rotate Array by 1
public class LeftRotateBy1 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int first = arr[0];
for (int i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
arr[arr.length - 1] = first;
for (int n : arr) System.out.print(n + " ");
// 10. Right Rotate Array by 1
public class RightRotateBy1 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int last = arr[arr.length - 1];
for (int i = arr.length - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = last;
for (int n : arr) System.out.print(n + " ");
// 11. Left Rotate Array by K
public class LeftRotateByK {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 2;
k %= arr.length;
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
reverse(arr, 0, arr.length - 1);
for (int n : arr) System.out.print(n + " ");
static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start++] = arr[end];
arr[end--] = temp;
// 12. Leader Elements in Array
public class LeadersInArray {
public static void main(String[] args) {
int[] arr = {16, 17, 4, 3, 5, 2};
int maxRight = Integer.MIN_VALUE;
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] > maxRight) {
System.out.print(arr[i] + " ");
maxRight = arr[i];
// 13. Kadane’s Algorithm – Maximum Subarray Sum
public class KadaneAlgorithm {
public static void main(String[] args) {
int[] arr = {-2, -3, 4, -1, -2, 1, 5, -3};
int maxSoFar = arr[0], maxEndingHere = arr[0];
for (int i = 1; i < arr.length; i++) {
maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
System.out.println("Maximum Subarray Sum: " + maxSoFar);
// 14. Find Union and Intersection of Two Arrays
import java.util.HashSet;
public class UnionIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 4, 5, 6, 7};
HashSet<Integer> union = new HashSet<>();
HashSet<Integer> intersection = new HashSet<>();
for (int num : arr1) union.add(num);
for (int num : arr2) {
if (union.contains(num)) intersection.add(num);
union.add(num);
System.out.println("Union: " + union);
System.out.println("Intersection: " + intersection);
// 15. Merge Two Sorted Arrays
import java.util.Arrays;
public class MergeSortedArrays {
public static void main(String[] args) {
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
int[] merged = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) merged[k++] = arr1[i++];
else merged[k++] = arr2[j++];
while (i < arr1.length) merged[k++] = arr1[i++];
while (j < arr2.length) merged[k++] = arr2[j++];
System.out.println("Merged Array: " + Arrays.toString(merged));
}
}
// 16. Check if Two Arrays are Equal
import java.util.Arrays;
public class ArraysEqual {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {3, 2, 1};
Arrays.sort(arr1);
Arrays.sort(arr2);
boolean isEqual = Arrays.equals(arr1, arr2);
System.out.println("Arrays equal? " + isEqual);
// 17. Find Pair with Given Sum
import java.util.HashSet;
public class PairWithSum {
public static void main(String[] args) {
int[] arr = {1, 4, 45, 6, 10, 8};
int sum = 16;
HashSet<Integer> set = new HashSet<>();
boolean found = false;
for (int num : arr) {
if (set.contains(sum - num)) {
System.out.println("Pair with given sum " + sum + " is (" + num + ", " + (sum - num) + ")");
found = true;
break;
set.add(num);
if (!found) System.out.println("No pair with given sum found");
// 18. Sort 0s, 1s and 2s (Dutch National Flag Problem)
public class Sort012 {
public static void main(String[] args) {
int[] arr = {0, 1, 2, 0, 1, 2};
int low = 0, mid = 0, high = arr.length - 1;
while (mid <= high) {
switch (arr[mid]) {
case 0: {
int temp = arr[low];
arr[low] = arr[mid];
arr[mid] = temp;
low++; mid++; break;
case 1:
mid++;
break;
case 2: {
int temp = arr[mid];
arr[mid] = arr[high];
arr[high] = temp;
high--;
break;
}
}
for (int n : arr) System.out.print(n + " ");
// 19. Prefix Sum Array – Range Sum Query
public class PrefixSum {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int[] prefix = new int[arr.length];
prefix[0] = arr[0];
for (int i = 1; i < arr.length; i++) {
prefix[i] = prefix[i - 1] + arr[i];
int l = 1, r = 3; // zero-based indices
int rangeSum = prefix[r] - (l == 0 ? 0 : prefix[l - 1]);
System.out.println("Range Sum (" + l + " to " + r + "): " + rangeSum);
// 20. Binary Search on Sorted Array
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low)/2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10};
int target = 6;
int index = binarySearch(arr, target);
System.out.println("Index of " + target + ": " + index);
// 21. Find Subarray with Given Sum (Positive Numbers)
public class SubarrayWithSum {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 7, 5};
int sum = 12;
int currSum = arr[0], start = 0;
for (int i = 1; i <= arr.length; i++) {
while (currSum > sum && start < i - 1) {
currSum -= arr[start];
start++;
if (currSum == sum) {
System.out.println("Subarray found from index " + start + " to " + (i - 1));
return;
if (i < arr.length) currSum += arr[i];
System.out.println("No subarray found");
// 22. Check if Array is Palindrome or Not
public class ArrayPalindrome {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 1};
boolean isPalindrome = true;
int start = 0, end = arr.length - 1;
while (start < end) {
if (arr[start] != arr[end]) {
isPalindrome = false;
break;
start++;
end--;
System.out.println("Array is palindrome? " + isPalindrome);
// ================= STRING-BASED PROBLEMS =================
// 1. Reverse a String
public class ReverseString {
public static void main(String[] args) {
String s = "hello";
String reversed = new StringBuilder(s).reverse().toString();
System.out.println("Reversed String: " + reversed);
// 2. Check Palindrome String
public class PalindromeString {
public static void main(String[] args) {
String s = "madam";
String rev = new StringBuilder(s).reverse().toString();
System.out.println("Is Palindrome? " + s.equals(rev));
// 3. Count Vowels and Consonants
public class CountVowelsConsonants {
public static void main(String[] args) {
String s = "hello world";
int vowels = 0, consonants = 0;
s = s.toLowerCase();
for (char c : s.toCharArray()) {
if (c >= 'a' && c <= 'z') {
if ("aeiou".indexOf(c) >= 0) vowels++;
else consonants++;
System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);
// 4. Check if Two Strings are Anagrams
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
if (s1.length() != s2.length()) {
System.out.println("Not Anagrams");
return;
}
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
System.out.println("Are Anagrams? " + Arrays.equals(arr1, arr2));
// 5. Find Duplicate Characters in String
import java.util.HashMap;
public class DuplicateChars {
public static void main(String[] args) {
String s = "programming";
HashMap<Character, Integer> freq = new HashMap<>();
for (char c : s.toCharArray()) freq.put(c, freq.getOrDefault(c, 0) + 1);
System.out.print("Duplicates: ");
for (var entry : freq.entrySet()) {
if (entry.getValue() > 1) System.out.print(entry.getKey() + " ");
// 6. Remove Duplicate Characters from a String
import java.util.LinkedHashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
String s = "banana";
LinkedHashSet<Character> set = new LinkedHashSet<>();
for (char c : s.toCharArray()) set.add(c);
StringBuilder sb = new StringBuilder();
for (char c : set) sb.append(c);
System.out.println("After Removing Duplicates: " + sb.toString());
// 7. Find First Non-Repeating Character
public class FirstNonRepeatingChar {
public static void main(String[] args) {
String s = "swiss";
int[] freq = new int[256];
for (char c : s.toCharArray()) freq[c]++;
for (char c : s.toCharArray()) {
if (freq[c] == 1) {
System.out.println("First Non-Repeating Character: " + c);
break;
// 8. Check if One String is Rotation of Another
public class StringRotation {
public static void main(String[] args) {
String s1 = "abcd";
String s2 = "cdab";
boolean isRotation = (s1.length() == s2.length()) && ((s1 + s1).contains(s2));
System.out.println("Is Rotation? " + isRotation);
// 9. Convert String to Integer (without using Integer.parseInt)
public class StringToInt {
public static void main(String[] args) {
String s = "12345";
int num = 0;
for (int i = 0; i < s.length(); i++) {
num = num * 10 + (s.charAt(i) - '0');
System.out.println("Converted Integer: " + num);
// 10. Check if String Contains Only Digits
public class OnlyDigits {
public static void main(String[] args) {
String s = "12345";
boolean onlyDigits = true;
for (char c : s.toCharArray()) {
if (!Character.isDigit(c)) {
onlyDigits = false;
break;
System.out.println("Contains only digits? " + onlyDigits);
// 11. Longest Word in a Sentence
public class LongestWord {
public static void main(String[] args) {
String sentence = "Java is a popular programming language";
String[] words = sentence.split("\\s+");
String longest = "";
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
System.out.println("Longest Word: " + longest);
// 12. Count Words in a Sentence
public class CountWords {
public static void main(String[] args) {
String sentence = "Java is a popular programming language";
String[] words = sentence.trim().split("\\s+");
System.out.println("Number of words: " + words.length);
// 13. Toggle Characters Case (Upper to Lower and vice versa)
public class ToggleCase {
public static void main(String[] args) {
String s = "Hello World!";
StringBuilder toggled = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isUpperCase(c)) {
toggled.append(Character.toLowerCase(c));
} else if (Character.isLowerCase(c)) {
toggled.append(Character.toUpperCase(c));
} else {
toggled.append(c);
}
}
System.out.println("Toggled Case: " + toggled.toString());
// 14. Check Pangram (Contains all letters A-Z)
public class CheckPangram {
public static void main(String[] args) {
String s = "The quick brown fox jumps over the lazy dog";
s = s.toLowerCase();
boolean[] mark = new boolean[26];
int index, count = 0;
for (int i = 0; i < s.length(); i++) {
if ('a' <= s.charAt(i) && s.charAt(i) <= 'z') {
index = s.charAt(i) - 'a';
if (!mark[index]) {
mark[index] = true;
count++;
System.out.println("Is Pangram? " + (count == 26));
// 15. Longest Palindromic Substring
public class LongestPalindromeSubstring {
public static void main(String[] args) {
String s = "babad";
String longest = "";
for (int i = 0; i < s.length(); i++) {
// Odd length palindrome
String odd = expandFromCenter(s, i, i);
if (odd.length() > longest.length()) longest = odd;
// Even length palindrome
String even = expandFromCenter(s, i, i + 1);
if (even.length() > longest.length()) longest = even;
System.out.println("Longest Palindromic Substring: " + longest);
static String expandFromCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
return s.substring(left + 1, right);
// 16. Print All Permutations of a String
public class StringPermutations {
public static void main(String[] args) {
String s = "ABC";
permute(s, 0, s.length() - 1);
static void permute(String s, int l, int r) {
if (l == r) {
System.out.println(s);
} else {
for (int i = l; i <= r; i++) {
s = swap(s, l, i);
permute(s, l + 1, r);
s = swap(s, l, i); // backtrack
static String swap(String s, int i, int j) {
char[] arr = s.toCharArray();
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return String.valueOf(arr);
// 17. Check if Two Strings are Isomorphic
public class IsomorphicStrings {
public static void main(String[] args) {
String s1 = "egg";
String s2 = "add";
System.out.println("Is Isomorphic? " + areIsomorphic(s1, s2));
static boolean areIsomorphic(String s1, String s2) {
if (s1.length() != s2.length()) return false;
int[] mapS = new int[256];
int[] mapT = new int[256];
for (int i = 0; i < s1.length(); i++) {
if (mapS[s1.charAt(i)] != mapT[s2.charAt(i)]) return false;
mapS[s1.charAt(i)] = i + 1;
mapT[s2.charAt(i)] = i + 1;
return true;
// 18. Find Repeated Substring Pattern
public class RepeatedSubstringPattern {
public static void main(String[] args) {
String s = "abab";
System.out.println("Has repeated substring pattern? " + repeatedSubstringPattern(s));
static boolean repeatedSubstringPattern(String s) {
String doubled = s + s;
String trimmed = doubled.substring(1, doubled.length() - 1);
return trimmed.contains(s);
// 19. Implement Substring Search (like indexOf)
public class SubstringSearch {
public static void main(String[] args) {
String text = "hello world";
String pattern = "world";
System.out.println("Index of pattern: " + indexOf(text, pattern));
static int indexOf(String text, String pattern) {
int n = text.length();
int m = pattern.length();
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if (text.charAt(i + j) != pattern.charAt(j)) break;
if (j == m) return i;
return -1;
// 20. String Compression (Count and Replace like "aaabb" -> "a3b2")
public class StringCompression {
public static void main(String[] args) {
String s = "aaabbc";
String compressed = compress(s);
System.out.println("Compressed String: " + compressed);
static String compress(String s) {
StringBuilder sb = new StringBuilder();
int count = 1;
for (int i = 1; i <= s.length(); i++) {
if (i == s.length() || s.charAt(i) != s.charAt(i - 1)) {
sb.append(s.charAt(i - 1));
if (count > 1) sb.append(count);
count = 1;
} else {
count++;
}
return sb.toString();