// Factor of a number
public class Factors {
public static void main(String[] args) {
int num = 28;
[Link]("Factors: ");
for (int i = 1; i <= num; i++) {
if (num % i == 0) [Link](i + " ");
// Prime Factors
public class PrimeFactors {
public static void main(String[] args) {
int num = 28;
[Link]("Prime Factors: ");
for (int i = 2; i <= num; i++) {
while (num % i == 0) {
[Link](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;
[Link]("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;
[Link]("Perfect Number: " + (sum == num));
// Perfect Square
public class PerfectSquare {
public static void main(String[] args) {
int num = 49;
int sqrt = (int)[Link](num);
[Link]("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 = [Link](num);
String squareStr = [Link](square);
[Link]("Automorphic: " + [Link](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;
[Link]("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;
[Link]("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;
[Link]("Friendly Pair: " + (ratio1 == ratio2));
// Positive or Negative
public class PositiveNegative {
public static void main(String[] args) {
int num = -5;
if (num > 0) [Link]("Positive");
else if (num < 0) [Link]("Negative");
else [Link]("Zero");
// Even or Odd
public class EvenOdd {
public static void main(String[] args) {
int num = 10;
[Link](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;
[Link]("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;
[Link]("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;
[Link]("Sum: " + sum);
}
// Greatest of two numbers
public class GreatestOfTwo {
public static void main(String[] args) {
int a = 10, b = 20;
[Link]("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;
[Link]("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));
[Link]("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 <= [Link](num); i++) {
if (num % i == 0) isPrime = false;
[Link]("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 <= [Link](num); i++) {
if (num % i == 0) {
isPrime = false;
break;
if (isPrime) [Link](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;
[Link]("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;
[Link]("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;
[Link]("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;
[Link]("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) [Link](original + " ");
// Fibonacci series up to n terms
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10, a = 0, b = 1;
[Link]("Fibonacci: ");
for (int i = 1; i <= n; i++) {
[Link](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;
[Link]("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;
[Link]("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;
[Link]("Power: " + result);
// LCM of two numbers
public class LCM {
public static void main(String[] args) {
int a = 12, b = 18;
int max = [Link](a, b);
int lcm = max;
while (true) {
if (lcm % a == 0 && lcm % b == 0) break;
lcm++;
[Link]("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;
[Link]("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;
[Link]("GCD: " + a);
// Binary to Decimal
public class BinaryToDecimal {
public static void main(String[] args) {
String binary = "1010";
int decimal = [Link](binary, 2);
[Link]("Decimal: " + decimal);
// Octal to Decimal
public class OctalToDecimal {
public static void main(String[] args) {
String octal = "17";
int decimal = [Link](octal, 8);
[Link]("Decimal: " + decimal);
// Hexadecimal to Decimal
public class HexToDecimal {
public static void main(String[] args) {
String hex = "1A";
int decimal = [Link](hex, 16);
[Link]("Decimal: " + decimal);
// Decimal to Binary
public class DecimalToBinary {
public static void main(String[] args) {
int num = 10;
[Link]("Binary: " + [Link](num));
// Decimal to Octal
public class DecimalToOctal {
public static void main(String[] args) {
int num = 15;
[Link]("Octal: " + [Link](num));
// Decimal to Hexadecimal
public class DecimalToHex {
public static void main(String[] args) {
int num = 26;
[Link]("Hexadecimal: " + [Link](num));
// Binary to Octal
public class BinaryToOctal {
public static void main(String[] args) {
String binary = "1010";
int decimal = [Link](binary, 2);
[Link]("Octal: " + [Link](decimal));
// Octal to Binary
public class OctalToBinary {
public static void main(String[] args) {
String octal = "12";
int decimal = [Link](octal, 8);
[Link]("Binary: " + [Link](decimal));
// Coordinate Quadrant
public class Quadrant {
public static void main(String[] args) {
int x = -3, y = 4;
if (x > 0 && y > 0) [Link]("Quadrant I");
else if (x < 0 && y > 0) [Link]("Quadrant II");
else if (x < 0 && y < 0) [Link]("Quadrant III");
else if (x > 0 && y < 0) [Link]("Quadrant IV");
else [Link]("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);
[Link]("Permutations: " + nPr);
// Maximum handshakes
public class Handshakes {
public static void main(String[] args) {
int n = 5;
int handshakes = n * (n - 1) / 2;
[Link]("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);
[Link]("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;
[Link]("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 <= [Link](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)) {
[Link](num + " = " + i + " + " + (num - i));
canBe = true;
break;
if (!canBe) [Link]("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 = [Link] * radius * radius;
[Link]("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 <= [Link](i); j++) {
if (i % j == 0) {
isPrime = false;
break;
if (isPrime) [Link](i + " ");
// Count digits
public class CountDigits {
public static void main(String[] args) {
int num = 12345, count = 0;
while (num > 0) {
count++;
num /= 10;
[Link]("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) [Link]("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];
[Link]([Link]());
// 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;
[Link]("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;
[Link]("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) [Link](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 + [Link](d)) / (2 * a);
double r2 = (-b - [Link](d)) / (2 * a);
[Link]("Roots: " + r1 + ", " + r2);
} else if (d == 0) {
double r = -b / (2 * a);
[Link]("One root: " + r);
} else {
[Link]("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) {
[Link](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) {
[Link](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 [Link](arr[n - 1], findMax(arr, n - 1));
public static void main(String[] args) {
int[] arr = {1, 4, 45, 6, -50};
[Link](findMax(arr, [Link]));
// Smallest element in array using recursion
public class MinInArray {
static int findMin(int[] arr, int n) {
if (n == 1) return arr[0];
return [Link](arr[n - 1], findMin(arr, n - 1));
public static void main(String[] args) {
int[] arr = {1, 4, 45, 6, -50};
[Link](findMin(arr, [Link]));
// 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) {
[Link](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) {
[Link](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) {
[Link](lcm(12, 18));
// String length using recursion
public class StringLengthRec {
static int length(String str) {
if ([Link]("")) return 0;
return 1 + length([Link](1));
public static void main(String[] args) {
[Link](length("Hello"));
// All Permutations of a String
public class Permutations {
static void permute(String str, String ans) {
if ([Link]() == 0) {
[Link](ans);
return;
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
String ros = [Link](0, i) + [Link](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) {
[Link](fib(7));
// Subset sum of array
public class SubsetSums {
static void subsetSums(int[] arr, int n, int index, int sum) {
if (index == n) {
[Link](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, [Link], 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;
[Link](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++) [Link](comb(n, i) + " ");
// Generate balanced parentheses
public class BalancedParentheses {
static void generate(int open, int close, String str) {
if (open == 0 && close == 0) {
[Link](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) {
[Link](fact(5));
// Palindromic partitions (basic)
public class PalindromicPartitions {
static boolean isPalindrome(String str) {
int i = 0, j = [Link]() - 1;
while (i < j) {
if ([Link](i++) != [Link](j--)) return false;
return true;
static void partition(String s, String out) {
if ([Link]() == 0) {
[Link](out);
return;
}
for (int i = 1; i <= [Link](); i++) {
String prefix = [Link](0, i);
if (isPalindrome(prefix)) {
partition([Link](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) {
[Link](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 ([Link]("")) {
[Link](ans);
return;
subsets([Link](1), ans);
subsets([Link](1), ans + [Link](0));
public static void main(String[] args) {
subsets("abc", "");
// Remove adjacent duplicates recursively
public class RemoveAdjDuplicates {
static String remove(String str) {
if ([Link]() <= 1) return str;
if ([Link](0) == [Link](1)) return remove([Link](1));
return [Link](0) + remove([Link](1));
public static void main(String[] args) {
[Link](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 < [Link]; i++) {
if (arr[i] > max) max = arr[i];
}
[Link]("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;
[Link]("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 < [Link] - 1; i++) {
if (arr[i] > arr[i + 1]) {
sorted = false;
break;
}
[Link]("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 = [Link] - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
for (int n : arr) [Link](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;
[Link]("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 < [Link]; i++) {
for (int j = i + 1; j < [Link]; j++) {
if (arr[i] == arr[j]) {
[Link]("Duplicate: " + arr[i]);
return;
// 7. Count Frequency of Each Element
import [Link];
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) [Link](num, [Link](num, 0) + 1);
[Link](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 < [Link]) arr[index++] = 0;
for (int n : arr) [Link](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 < [Link] - 1; i++) {
arr[i] = arr[i + 1];
arr[[Link] - 1] = first;
for (int n : arr) [Link](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[[Link] - 1];
for (int i = [Link] - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = last;
for (int n : arr) [Link](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 %= [Link];
reverse(arr, 0, k - 1);
reverse(arr, k, [Link] - 1);
reverse(arr, 0, [Link] - 1);
for (int n : arr) [Link](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 = [Link] - 1; i >= 0; i--) {
if (arr[i] > maxRight) {
[Link](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 < [Link]; i++) {
maxEndingHere = [Link](arr[i], maxEndingHere + arr[i]);
maxSoFar = [Link](maxSoFar, maxEndingHere);
[Link]("Maximum Subarray Sum: " + maxSoFar);
// 14. Find Union and Intersection of Two Arrays
import [Link];
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) [Link](num);
for (int num : arr2) {
if ([Link](num)) [Link](num);
[Link](num);
[Link]("Union: " + union);
[Link]("Intersection: " + intersection);
// 15. Merge Two Sorted Arrays
import [Link];
public class MergeSortedArrays {
public static void main(String[] args) {
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
int[] merged = new int[[Link] + [Link]];
int i = 0, j = 0, k = 0;
while (i < [Link] && j < [Link]) {
if (arr1[i] < arr2[j]) merged[k++] = arr1[i++];
else merged[k++] = arr2[j++];
while (i < [Link]) merged[k++] = arr1[i++];
while (j < [Link]) merged[k++] = arr2[j++];
[Link]("Merged Array: " + [Link](merged));
}
}
// 16. Check if Two Arrays are Equal
import [Link];
public class ArraysEqual {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {3, 2, 1};
[Link](arr1);
[Link](arr2);
boolean isEqual = [Link](arr1, arr2);
[Link]("Arrays equal? " + isEqual);
// 17. Find Pair with Given Sum
import [Link];
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 ([Link](sum - num)) {
[Link]("Pair with given sum " + sum + " is (" + num + ", " + (sum - num) + ")");
found = true;
break;
[Link](num);
if (!found) [Link]("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 = [Link] - 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) [Link](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[[Link]];
prefix[0] = arr[0];
for (int i = 1; i < [Link]; 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]);
[Link]("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 = [Link] - 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);
[Link]("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 <= [Link]; i++) {
while (currSum > sum && start < i - 1) {
currSum -= arr[start];
start++;
if (currSum == sum) {
[Link]("Subarray found from index " + start + " to " + (i - 1));
return;
if (i < [Link]) currSum += arr[i];
[Link]("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 = [Link] - 1;
while (start < end) {
if (arr[start] != arr[end]) {
isPalindrome = false;
break;
start++;
end--;
[Link]("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();
[Link]("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();
[Link]("Is Palindrome? " + [Link](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 = [Link]();
for (char c : [Link]()) {
if (c >= 'a' && c <= 'z') {
if ("aeiou".indexOf(c) >= 0) vowels++;
else consonants++;
[Link]("Vowels: " + vowels + ", Consonants: " + consonants);
// 4. Check if Two Strings are Anagrams
import [Link];
public class AnagramCheck {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
if ([Link]() != [Link]()) {
[Link]("Not Anagrams");
return;
}
char[] arr1 = [Link]();
char[] arr2 = [Link]();
[Link](arr1);
[Link](arr2);
[Link]("Are Anagrams? " + [Link](arr1, arr2));
// 5. Find Duplicate Characters in String
import [Link];
public class DuplicateChars {
public static void main(String[] args) {
String s = "programming";
HashMap<Character, Integer> freq = new HashMap<>();
for (char c : [Link]()) [Link](c, [Link](c, 0) + 1);
[Link]("Duplicates: ");
for (var entry : [Link]()) {
if ([Link]() > 1) [Link]([Link]() + " ");
// 6. Remove Duplicate Characters from a String
import [Link];
public class RemoveDuplicates {
public static void main(String[] args) {
String s = "banana";
LinkedHashSet<Character> set = new LinkedHashSet<>();
for (char c : [Link]()) [Link](c);
StringBuilder sb = new StringBuilder();
for (char c : set) [Link](c);
[Link]("After Removing Duplicates: " + [Link]());
// 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 : [Link]()) freq[c]++;
for (char c : [Link]()) {
if (freq[c] == 1) {
[Link]("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 = ([Link]() == [Link]()) && ((s1 + s1).contains(s2));
[Link]("Is Rotation? " + isRotation);
// 9. Convert String to Integer (without using [Link])
public class StringToInt {
public static void main(String[] args) {
String s = "12345";
int num = 0;
for (int i = 0; i < [Link](); i++) {
num = num * 10 + ([Link](i) - '0');
[Link]("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 : [Link]()) {
if () {
onlyDigits = false;
break;
[Link]("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 = [Link]("\\s+");
String longest = "";
for (String word : words) {
if ([Link]() > [Link]()) {
longest = word;
[Link]("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 = [Link]().split("\\s+");
[Link]("Number of words: " + [Link]);
// 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 : [Link]()) {
if ([Link](c)) {
[Link]([Link](c));
} else if ([Link](c)) {
[Link]([Link](c));
} else {
[Link](c);
}
}
[Link]("Toggled Case: " + [Link]());
// 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 = [Link]();
boolean[] mark = new boolean[26];
int index, count = 0;
for (int i = 0; i < [Link](); i++) {
if ('a' <= [Link](i) && [Link](i) <= 'z') {
index = [Link](i) - 'a';
if (!mark[index]) {
mark[index] = true;
count++;
[Link]("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 < [Link](); i++) {
// Odd length palindrome
String odd = expandFromCenter(s, i, i);
if ([Link]() > [Link]()) longest = odd;
// Even length palindrome
String even = expandFromCenter(s, i, i + 1);
if ([Link]() > [Link]()) longest = even;
[Link]("Longest Palindromic Substring: " + longest);
static String expandFromCenter(String s, int left, int right) {
while (left >= 0 && right < [Link]() && [Link](left) == [Link](right)) {
left--;
right++;
return [Link](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, [Link]() - 1);
static void permute(String s, int l, int r) {
if (l == r) {
[Link](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 = [Link]();
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return [Link](arr);
// 17. Check if Two Strings are Isomorphic
public class IsomorphicStrings {
public static void main(String[] args) {
String s1 = "egg";
String s2 = "add";
[Link]("Is Isomorphic? " + areIsomorphic(s1, s2));
static boolean areIsomorphic(String s1, String s2) {
if ([Link]() != [Link]()) return false;
int[] mapS = new int[256];
int[] mapT = new int[256];
for (int i = 0; i < [Link](); i++) {
if (mapS[[Link](i)] != mapT[[Link](i)]) return false;
mapS[[Link](i)] = i + 1;
mapT[[Link](i)] = i + 1;
return true;
// 18. Find Repeated Substring Pattern
public class RepeatedSubstringPattern {
public static void main(String[] args) {
String s = "abab";
[Link]("Has repeated substring pattern? " + repeatedSubstringPattern(s));
static boolean repeatedSubstringPattern(String s) {
String doubled = s + s;
String trimmed = [Link](1, [Link]() - 1);
return [Link](s);
// 19. Implement Substring Search (like indexOf)
public class SubstringSearch {
public static void main(String[] args) {
String text = "hello world";
String pattern = "world";
[Link]("Index of pattern: " + indexOf(text, pattern));
static int indexOf(String text, String pattern) {
int n = [Link]();
int m = [Link]();
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if ([Link](i + j) != [Link](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);
[Link]("Compressed String: " + compressed);
static String compress(String s) {
StringBuilder sb = new StringBuilder();
int count = 1;
for (int i = 1; i <= [Link](); i++) {
if (i == [Link]() || [Link](i) != [Link](i - 1)) {
[Link]([Link](i - 1));
if (count > 1) [Link](count);
count = 1;
} else {
count++;
}
return [Link]();