Here’s a detailed guide on Java String and Array interview questions, complete with explanations and examples:
1. Reverse a String
Reversing a string is one of the most commonly asked interview questions.
Example:
public class ReverseString {
public static void main(String[] args) {
String input = "hello";
String reversed = new StringBuilder(input).reverse().toString();
System.out.println("Reversed String: " + reversed);
}
}
Explanation:
StringBuilder.reverse()
: Efficiently reverses a string.- Alternative: Use a loop to reverse character by character.
2. Check if a String is a Palindrome
A string is a palindrome if it reads the same backward as forward.
Example:
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
if (str.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
Explanation:
- Reverse the string and compare it with the original.
3. Find Duplicate Characters in a String
Example:
import java.util.*;
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
Map<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
System.out.println("Duplicate Characters:");
charCount.forEach((key, value) -> {
if (value > 1) System.out.println(key + ": " + value);
});
}
}
Explanation:
- Use a
HashMap
to store character frequencies. - Print characters with a count greater than 1.
4. Remove Vowels from a String
Example:
public class RemoveVowels {
public static void main(String[] args) {
String str = "beautiful";
String result = str.replaceAll("[aeiouAEIOU]", "");
System.out.println("String without vowels: " + result);
}
}
Explanation:
replaceAll
: Removes all vowels using a regex.
5. Check if Two Strings are Anagrams
Two strings are anagrams if they have the same characters in the same frequency.
Example:
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
if (Arrays.equals(arr1, arr2)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}
}
Explanation:
- Sort both strings and compare the sorted arrays.
6. Find the First Non-Repeated Character
Example:
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstNonRepeated {
public static void main(String[] args) {
String str = "swiss";
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) {
System.out.println("First non-repeated character: " + entry.getKey());
break;
}
}
}
}
Explanation:
- Use a
LinkedHashMap
to maintain insertion order.
7. Rotate an Array
Example:
import java.util.Arrays;
public class RotateArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 2; // Number of rotations
rotate(arr, k);
System.out.println("Rotated Array: " + Arrays.toString(arr));
}
private static void rotate(int[] arr, int k) {
k %= arr.length;
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
}
private static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}
Explanation:
- Reverse the entire array.
- Reverse the first
k
elements. - Reverse the remaining elements.
8. Find the Maximum Subarray Sum (Kadane’s Algorithm)
Example:
public class MaxSubarraySum {
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println("Maximum Subarray Sum: " + maxSubArraySum(arr));
}
private static int maxSubArraySum(int[] arr) {
int maxSoFar = arr[0];
int maxEndingHere = arr[0];
for (int i = 1; i < arr.length; i++) {
maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
}
Explanation:
- Use a single loop to calculate the maximum sum ending at each index.
9. Find the Intersection of Two Arrays
Example:
import java.util.*;
public class ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 2, 3};
int[] arr2 = {2, 3, 4};
Set<Integer> set1 = new HashSet<>();
for (int num : arr1) set1.add(num);
Set<Integer> result = new HashSet<>();
for (int num : arr2) {
if (set1.contains(num)) result.add(num);
}
System.out.println("Intersection: " + result);
}
}
Explanation:
- Use a
HashSet
to store elements from one array and check for matches in the other.
10. Merge Two Sorted Arrays
Example:
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 = merge(arr1, arr2);
System.out.println("Merged Array: " + Arrays.toString(merged));
}
private static int[] merge(int[] arr1, int[] arr2) {
int[] result = 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]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
while (i < arr1.length) result[k++] = arr1[i++];
while (j < arr2.length) result[k++] = arr2[j++];
return result;
}
}
Explanation:
- Use two pointers to merge elements in sorted order.
Pro Tips for Interview:
- String Pool: Be ready to explain how strings are stored in the string pool and why they are immutable.
- Array vs. ArrayList:
- Arrays are fixed in size, while
ArrayList
is dynamic.
- Arrays are fixed in size, while
- Edge Cases: Always discuss edge cases like empty strings, single-element arrays, etc.
- Optimize: Use algorithms like Kadane’s for array problems to optimize performance.
Let me know if you'd like further explanations or additional examples! 😊