Beginner
1. Reverse a number
public class NumReverse {
public static int reverse(int number) {
int reverse = 0;
int reminder;
while (number > 0) {
reminder = number % 10;
reverse = (reverse * 10) + reminder;
number = number / 10;
}
return reverse;
}
public static void main(String[] args) {
int number = 358;
System.out.println("Reversed Number is:" + reverse(number));
}
}
Output
Reversed Number is:853
2. Reverse a number with Recursion
public class NumReverseWithRecursion {
static int reverse = 0;
static void reverse(int number){
if(number<=0)
return;
int reminder = number % 10;
reverse = (reverse * 10) + reminder;
reverse(number / 10);
}
public static void main(String[] args) {
int number = 1234;
reverse(number);
System.out.print("Reversed Number is: " + reverse);
}
}
Output:
Reversed Number is: 4321
3. Reverse using StringBuilder
public class StringBuilderReverse {
public static void main(String[] args) {
int number = 123456;
String temp = ""+number;
StringBuilder sb = new StringBuilder(temp);
StringBuilder str = sb.reverse();
System.out.println("Reversed String is: "+str.toString());
}
}
Output:
Reversed String is: 654321
4. Reverse a String
public static String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
5. FizzBuzz (1–100)
public static void fizzBuzz() {
for (int i = 1; i <= 100; i++) {
if (i % 15 == 0) System.out.println("FizzBuzz");
else if (i % 3 == 0) System.out.println("Fizz");
else if (i % 5 == 0) System.out.println("Buzz");
else System.out.println(i);
}
}
6. Two Sum
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[0];
}
7. Palindrome Check
public static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) return false;
i++; j--;
}
return true;
}
8. Missing Number
public static int missingNumber(int[] nums) {
int n = nums.length;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : nums) actualSum += num;
return expectedSum - actualSum;
}
9. Detect Duplicates
public static boolean hasDuplicates(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) return true;
}
return false;
}
10. Reverse Linked List
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
11. Binary Search
public static int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
12. Merge Sort
public static void mergeSort(int[] arr, int l, int r) {
if (l < r) {
int m = (l + r) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
private static void merge(int[] arr, int l, int m, int r) {
int n1 = m - l + 1, n2 = r - m;
int[] L = new int[n1], R = new int[n2];
for (int i = 0; i < n1; i++) L[i] = arr[l + i];
for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}
13. Second Largest Number
public static int secondLargest(int[] nums) {
int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : nums) {
if (num > max) {
second = max;
max = num;
} else if (num > second && num != max) {
second = num;
}
}
return second;
}
14. Check Prime Number
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
15. Fibonacci (Recursion)
public static int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
16. Count Words in a Sentence
public static int countWords(String s) {
s = s.trim();
if (s.isEmpty()) return 0;
return s.split("\\s+").length;
}
17. Shuffle an Array
public static void shuffleArray(int[] a) {
Random rand = new Random();
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(a.length);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
18. Reverse String Without Built-In
public static String reverseManual(String s) {
char[] c = s.toCharArray();
for (int i = 0; i < c.length / 2; i++) {
char temp = c[i];
c[i] = c[c.length - 1 - i];
c[c.length - 1 - i] = temp;
}
return new String(c);
}
19. Remove Spaces
public static String removeSpaces(String s) {
return s.replaceAll("\\s", "");
}
20. Trim Leading and Trailing Spaces
public static String trimSpaces(String s) {
return s.strip();
}
21. Sort an Array
public static void sortArray(int[] a) {
Arrays.sort(a);
}
22. Check If Only Odds
public static boolean onlyOdds(List<Integer> list) {
return list.stream().allMatch(x -> x % 2 != 0);
}
23. Factorial
public static long factorial(int n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
24. Swap Two Numbers Without Temp
public static void swap(int a, int b) {
a = a + b;
b = a - b;
a = a - b;
System.out.println("a=" + a + " b=" + b);
}
25. Count Distinct Characters
public static Map<Character, Integer> countDistinctChars(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
return map;
}
26. Immutable String Demo
public static void immutableDemo() {
String s1 = "";
String s2 = s1;
s1 = "Python";
System.out.println("s1: " + s1); // Python
System.out.println("s2: " + s2); //
}
27. Character Pyramid
public static void printPyramid(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n - i; j++) System.out.print(" ");
for (int j = 0; j < 2 * i - 1; j++) System.out.print("*");
System.out.println();
}
}
28. Exception Handling
public static void fileReadDemo() {
try {
FileInputStream fis = new FileInputStream("file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
29. Deadlock Example
static class Deadlock {
final Object lock1 = new Object();
final Object lock2 = new Object();
public void method1() {
synchronized (lock1) {
synchronized (lock2) {
System.out.println("Method 1");
}
}
}
public void method2() {
synchronized (lock2) {
synchronized (lock1) {
System.out.println("Method 2");
}
}
}
}
30. Enum Example
enum State { START, RUNNING, WAITING, DEAD }
31. Text Blocks Example ( 15+)
public static void textBlockExample() {
String text = """
Line1
Line2
""";
System.out.println(text);
}
32. Max Depth of Binary Tree
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static int maxDepth(TreeNode root) {
return (root == null) ? 0 : 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
33. Check if a number is a palindrome
public boolean isPalindrome(int x) {
int original = x, reversed = 0;
while (x > 0) {
reversed = reversed * 10 + x % 10;
x /= 10;
}
return original == reversed;
}
34. Check if two strings are anagrams
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
count[t.charAt(i) - 'a']--;
}
for (int i : count)
if (i != 0) return false;
return true;
}
35. Find duplicate number in array
public int findDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (!seen.add(num)) return num;
}
return -1;
}
36. Find first non-repeating character in a string
public int firstUniqChar(String s) {
int[] freq = new int[26];
for (char c : s.toCharArray())
freq[c - 'a']++;
for (int i = 0; i < s.length(); i++)
if (freq[s.charAt(i) - 'a'] == 1)
return i;
return -1;
}
37. Check if string is a rotation of another
public boolean isRotation(String s1, String s2) {
return s1.length() == s2.length() && (s1 + s1).contains(s2);
}
38. Count vowels and consonants in a string
public void countVowelsAndConsonants(String str) {
int vowels = 0, consonants = 0;
for (char c : str.toLowerCase().toCharArray()) {
if (Character.isLetter(c)) {
if ("aeiou".indexOf(c) != -1)
vowels++;
else
consonants++;
}
}
System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);
}
39. Find maximum occurring character in a string
public char maxOccurringChar(String str) {
int[] count = new int[256];
for (char c : str.toCharArray())
count[c]++;
int max = 0;
char result = ' ';
for (int i = 0; i < 256; i++)
if (count[i] > max) {
max = count[i];
result = (char) i;
}
return result;
}
40. Check if a number is Armstrong
public boolean isArmstrong(int n) {
int original = n, sum = 0;
int digits = String.valueOf(n).length();
while (n > 0) {
int r = n % 10;
sum += Math.pow(r, digits);
n /= 10;
}
return sum == original;
}
41. Find power of a number (x^n)
public double power(double x, int n) {
if (n == 0) return 1;
if (n < 0) return 1 / power(x, -n);
double half = power(x, n / 2);
return (n % 2 == 0) ? half * half : x * half * half;
}
42. Move all zeros to end of array
public void moveZeros(int[] nums) {
int index = 0;
for (int num : nums)
if (num != 0)
nums[index++] = num;
while (index < nums.length)
nums[index++] = 0;
}
43. Remove duplicates from array
public int[] removeDuplicates(int[] nums) {
return Arrays.stream(nums).distinct().toArray();
}
44. Find second largest number in array
public int secondLargest(int[] nums) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : nums) {
if (n > first) {
second = first;
first = n;
} else if (n > second && n != first) {
second = n;
}
}
return second;
}
45. Check if a string is a palindrome
public 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;
}
46. Find factorial of a number
public int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
47. Binary Search
public int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
48. Check if number is power of two
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
49. Find GCD of two numbers
public int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
50. Fibonacci with memoization
Map<Integer, Integer> memo = new HashMap<>();
public int fib(int n) {
if (n <= 1) return n;
if (memo.containsKey(n)) return memo.get(n);
int result = fib(n - 1) + fib(n - 2);
memo.put(n, result);
return result;
}
51. Find majority element (appears more than n/2 times)
public int majorityElement(int[] nums) {
int count = 0, candidate = 0;
for (int num : nums) {
if (count == 0) candidate = num;
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
52. Check if a string is valid IP
public boolean isValidIP(String ip) {
String[] parts = ip.split("\\.");
if (parts.length != 4) return false;
for (String part : parts) {
try {
int n = Integer.parseInt(part);
if (n < 0 || n > 255) return false;
} catch (NumberFormatException e) {
return false;
}
}
return true;
}
53. Find missing number in sequence
public int missingNumber(int[] nums) {
int n = nums.length;
int expected = n * (n + 1) / 2;
int actual = 0;
for (int num : nums) actual += num;
return expected - actual;
}
54. Merge two sorted arrays
public int[] merge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
result[k++] = a[i] < b[j] ? a[i++] : b[j++];
while (i < a.length) result[k++] = a[i++];
while (j < b.length) result[k++] = b[j++];
return result;
}
55. Find peak element in array
public int findPeak(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[mid + 1])
right = mid;
else
left = mid + 1;
}
return left;
}
56. Implement Queue using 2 stacks
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
public void enqueue(int x) {
s1.push(x);
}
public int dequeue() {
if (s2.isEmpty())
while (!s1.isEmpty())
s2.push(s1.pop());
return s2.isEmpty() ? -1 : s2.pop();
}
57. Check for Pangram
public boolean isPangram(String str) {
Set<Character> set = new HashSet<>();
for (char c : str.toLowerCase().toCharArray()) {
if (Character.isLetter(c)) set.add(c);
}
return set.size() == 26;
}
58. Find intersection of two arrays
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> result = new HashSet<>();
for (int n : nums1) set1.add(n);
for (int n : nums2)
if (set1.contains(n)) result.add(n);
return result.stream().mapToInt(i -> i).toArray();
}
59. Check if matrix is symmetric
public boolean isSymmetric(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (matrix[i][j] != matrix[j][i])
return false;
return true;
}
60. Check if year is a leap year
public boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}