Coding challenges are a staple of technical interviews. They assess your problem-solving abilities and coding skills in real-time. Common challenges may involve algorithms, data structures, and logic puzzles.
To explore various coding challenges and solutions, refer to our article: Java Coding Challenges.
Write a method to reverse a given string.
public String reverseString(String str) {
return new StringBuilder(str).reverse().toString();
}
Write a method to check if a given string is a palindrome.
public boolean isPalindrome(String str) {
String reversed = new StringBuilder(str).reverse().toString();
return str.equals(reversed);
}
Write a method to calculate the factorial of a given number.
public int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
Write a method to generate the Fibonacci series up to a given number.
public List<Integer> fibonacci(int n) {
List<Integer> fib = new ArrayList<>();
int a = 0, b = 1;
while (a < n) {
fib.add(a);
int temp = a;
a = b;
b = temp + b;
}
return fib;
}
Write a method to check if a given number is prime.
public 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;
}
Write a method to find the largest element in an array.
public int findLargest(int[] arr) {
int max = arr[0];
for (int num : arr) {
if (num > max) max = num;
}
return max;
}
Write a method to count the number of vowels in a given string.
public int countVowels(String str) {
int count = 0;
for (char c : str.toCharArray()) {
if ("aeiouAEIOU".indexOf(c) != -1) count++;
}
return count;
}
Write a method to remove duplicates from an array.
public int[] removeDuplicates(int[] arr) {
return Arrays.stream(arr).distinct().toArray();
}
Write a method to merge two sorted arrays into a single sorted array.
public int[] mergeSortedArrays(int[] arr1, int[] arr2) {
int[] merged = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, merged, 0, arr1.length);
System.arraycopy(arr2, 0, merged, arr1.length, arr2.length);
Arrays.sort(merged);
return merged;
}
Write a method to find the second largest element in an array.
public int findSecondLargest(int[] arr) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num <> first) {
second = num;
}
}
return second;
}
Write a method to check if two strings are anagrams of each other.
public boolean areAnagrams(String str1, String str2) {
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
Write a method to find the missing number in an array of integers from 1 to n.
public int findMissingNumber(int[] arr, int n) {
int total = n * (n + 1) / 2;
int sum = 0;
for (int num : arr) {
sum += num;
}
return total - sum;
}
Write a method to check if the parentheses in a string are balanced.
public boolean isBalanced(String str) {
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray()) {
if (c == '(') stack.push(c);
else if (c == ')') {
if (stack.isEmpty()) return false;
stack.pop();
}
}
return stack.isEmpty();
}
Write a method to find the greatest common divisor (GCD) of two numbers.
public int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
Write a method to find the least common multiple (LCM) of two numbers.
public int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
Write a method to count the number of words in a given string.
public int countWords(String str) {
return str.trim().isEmpty() ? 0 : str.trim().split("\\s+").length;
}
Write a method to find the intersection of two arrays.
public int[] intersection(int[] arr1, int[] arr2) {
Set<Integer> set1 = new HashSet<>();
for (int num : arr1) set1.add(num);
return Arrays.stream(arr2).filter(set1::contains).distinct().toArray();
}
Write a method to find the union of two arrays.
public int[] union(int[] arr1, int[] arr2) {
Set<Integer> set = new HashSet<>();
for (int num : arr1) set.add(num);
for (int num : arr2) set.add(num);
return set.stream().mapToInt(i -> i).toArray();
}
Write a method to find the Kth largest element in an array.
public int findKthLargest(int[] arr, int k) {
Arrays.sort(arr);
return arr[arr.length - k];
}
Write a method to rotate an array to the right by a given number of steps.
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start++] = nums[end];
nums[end--] = temp;
}
}
Write a method to find the first non-repeating character in a string.
public char firstNonRepeating(String str) {
Map<Character, Integer> charCount = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
if (entry.getValue() == 1) return entry.getKey();
}
return '\0'; // Return null character if not found
}
Write a method to check if two strings are rotations of each other.
public boolean areRotations(String str1, String str2) {
if (str1.length() != str2.length()) return false;
String temp = str1 + str1;
return temp.contains(str2);
}
Write a method to find the longest common prefix among an array of strings.
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
}
return prefix;
}
Write a method to find the missing number in a sequence from 1 to n.
public int findMissing(int[] arr, int n) {
int total = n * (n + 1) / 2;
int sum = 0;
for (int num : arr) {
sum += num;
}
return total - sum;
}
Write a method to check if a string contains only digits.
public boolean isNumeric(String str) {
return str.matches("\\d+");
}
Write a method to find the sum of digits in a given number.
public int sumOfDigits(int n) {
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
Write a method to check if a number is an Armstrong number.
public boolean isArmstrong(int n) {
int sum = 0, temp = n, digits = String.valueOf(n).length();
while (temp != 0) {
int digit = temp % 10;
sum += Math.pow(digit, digits);
temp /= 10;
}
return sum == n;
}
Write a method to find the intersection of two arrays.
public int[] intersection(int[] arr1, int[] arr2) {
Set<Integer> set1 = new HashSet<>();
for (int num : arr1) set1.add(num);
return Arrays.stream(arr2).filter(set1::contains).distinct().toArray();
}
Write a method to find the union of two arrays.
public int[] union(int[] arr1, int[] arr2) {
Set<Integer> set = new HashSet<>();
for (int num : arr1) set.add(num);
for (int num : arr2) set.add(num);
return set.stream().mapToInt(i -> i).toArray();
}
Write a method to find the Kth smallest element in an array.
public int findKthSmallest(int[] arr, int k) {
Arrays.sort(arr);
return arr[k - 1];
}
Write a method to check if one string is a substring of another.
public boolean isSubstring(String str1, String str2) {
return str1.contains(str2);
}
Write a method to find the length of the longest increasing subsequence in an array.
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return Arrays.stream(dp).max().getAsInt();
}
Write a method to find the minimum element in a rotated sorted array.
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left];
}
Write a method to find the majority element in an array (element that appears more than n/2 times).
public int majorityElement(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
if (countMap.get(num) > nums.length / 2) return num;
}
return -1; // No majority element
}
Write a method to find the longest palindromic substring in a given string.
public String longestPalindrome(String s) {
if (s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
Write a method to find the first repeating character in a string.
public char firstRepeating(String str) {
Set<Character> seen = new HashSet<>();
for (char c : str.toCharArray()) {
if (seen.contains(c)) return c;
seen.add(c);
}
return '\0'; // Return null character if not found
}
Write a method to find the maximum product of two integers in an array.
public int maxProduct(int[] nums) {
Arrays.sort(nums);
return nums[nums.length - 1] * nums[nums.length - 2];
}
Write a method to check if one string is a rotation of another.
public boolean isRotation(String str1, String str2) {
if (str1.length() != str2.length()) return false;
String temp = str1 + str1;
return temp.contains(str2);
}
Write a method to find the length of the longest substring without repeating characters.
public int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int left = 0, maxLength = 0;
for (int right = 0; right < s.length(); right++) {
while (set.contains(s.charAt(right))) {
set.remove(s.charAt(left++));
}
set.add(s.charAt(right));
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
Write a method to find the minimum element in a rotated sorted array.
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left];
}
Write a method to find the length of the longest consecutive elements sequence.
public int longestConsecutive(int[] nums) {
Set<Integer> numSet = new HashSet<>();
for (int num : nums) numSet.add(num);
int longestStreak = 0;
for (int num : numSet) {
if (!numSet.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (numSet.contains(currentNum + 1)) {
currentNum++;
currentStreak++;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
Write a method to find the number of islands in a 2D grid.
public int numIslands(char[][] grid) {
if (grid.length == 0) return 0;
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
count++;
dfs(grid, i, j);
}
}
}
return count;
}
private void dfs(char[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') return;
grid[i][j] = '0'; // Mark as visited
dfs(grid, i + 1, j);
dfs(grid, i - 1, j);
dfs(grid, i, j + 1);
dfs(grid, i, j - 1);
}
Write a method to find the diameter of a binary tree.
public int diameterOfBinaryTree(TreeNode root) {
int[] diameter = new int[1];
depth(root, diameter);
return diameter[0];
}
private int depth(TreeNode node, int[] diameter) {
if (node == null) return 0;
int left = depth(node.left, diameter);
int right = depth(node.right, diameter);
diameter[0] = Math.max(diameter[0], left + right);
return Math.max(left, right) + 1;
}
Write methods to serialize and deserialize a binary tree.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serializeHelper(root, sb);
return sb.toString();
}
private void serializeHelper(TreeNode node, StringBuilder sb) {
if (node == null) {
sb.append("null,");
return;
}
sb.append(node.val).append(",");
serializeHelper(node.left, sb);
serializeHelper(node.right, sb);
}
public TreeNode deserialize(String data) {
String[] nodes = data.split(",");
Queue<String> queue = new LinkedList<>(Arrays.asList(nodes));
return deserializeHelper(queue);
}
private TreeNode deserializeHelper(Queue<String> queue) {
String val = queue.poll();
if (val.equals("null")) return null;
TreeNode node = new TreeNode(Integer.parseInt(val));
node.left = deserializeHelper(queue);
node.right = deserializeHelper(queue);
return node;
}
Write a method to find the lowest common ancestor of two nodes in a binary tree.
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
return left == null ? right : right == null ? left : root;
}
Write a method to find the maximum depth of a binary tree.
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
Write a method to check if a binary tree is height-balanced.
public boolean isBalanced(TreeNode root) {
return checkHeight(root) != -1;
}
private int checkHeight(TreeNode node) {
if (node == null) return 0;
int leftHeight = checkHeight(node.left);
if (leftHeight == -1) return -1;
int rightHeight = checkHeight(node.right);
if (rightHeight == -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return Math.max(leftHeight, rightHeight) + 1;
}
Write a method to check if a binary tree has a root-to-leaf path with a given sum.
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return sum == 0;
sum -= root.val;
if (root.left == null && root.right == null) return sum == 0;
return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
}
Write a method to find the maximum path sum in a binary tree.
public int maxPathSum(TreeNode root) {
int[] maxSum = new int[1];
maxPath(root, maxSum);
return maxSum[0];
}
private int maxPath(TreeNode node, int[] maxSum) {
if (node == null) return 0;
int left = Math.max(maxPath(node.left, maxSum), 0);
int right = Math.max(maxPath(node.right, maxSum), 0);
maxSum[0] = Math.max(maxSum[0], node.val + left + right);
return node.val + Math.max(left, right);
}
Write a method to find the diameter of a binary tree.
public int diameterOfBinaryTree(TreeNode root) {
int[] diameter = new int[1];
depth(root, diameter);
return diameter[0];
}
private int depth(TreeNode node, int[] diameter) {
if (node == null) return 0;
int left = depth(node.left, diameter);
int right = depth(node.right, diameter);
diameter[0] = Math.max(diameter[0], left + right);
return Math.max(left, right) + 1;
}