1. Valid Anagram
Given two strings s and t, determine if they are anagrams — i.e., contain the exact same characters with the same frequencies.
Since characters are constrained to lowercase English letters, a fixed-size integer array of length 26 suffices for counting frequencies.
public boolean checkAnagram(String text1, String text2) {
if (text1.length() != text2.length()) return false;
int[] freq = new int[26];
for (char c : text1.toCharArray()) {
freq[c - 'a']++;
}
for (char c : text2.toCharArray()) {
freq[c - 'a']--;
}
for (int count : freq) {
if (count != 0) return false;
}
return true;
}
This approach ensures linear time O(n) and constant space O(1).
2. Intersection of Two Arrays
Given two integer arrays, return unique elements present in both — the mathematical intersection.
First, store distinct elements of the first array using a Set. Then, scan the second array andcollect elements found in the first, leveraging HashSet for duplicate-free results.
public int[] findCommonUnique(int[] arrA, int[] arrB) {
if (arrA.length == 0 || arrB.length == 0) return new int[0];
Set<integer> seen = new HashSet<>();
Set<integer> intersection = new HashSet<>();
for (int num : arrA) {
seen.add(num);
}
for (int num : arrB) {
if (seen.contains(num)) {
intersection.add(num);
}
}
return intersection.stream().mapToInt(Integer::intValue).toArray();
}
</integer></integer>
Time complexity is O(m + n), and space is O(m + n) in the worst case.
3. Happy Number
A happy number is one where repeated replacing the number with the sum of squares of its digits eventually yields 1. Otherwise, it falls in to a loop.
To detect cycles, maintain a HashSet of intermediate values. Revisiting a value means a loop — return false. Reaching 1 means success.
public boolean isLuckyNumber(int num) {
Set<integer> visited = new HashSet<>();
while (num != 1 && !visited.contains(num)) {
visited.add(num);
num = computeDigitSquareSum(num);
}
return num == 1;
}
private int computeDigitSquareSum(int value) {
int total = 0;
while (value > 0) {
int digit = value % 10;
total += digit * digit;
value /= 10;
}
return total;
}
</integer>
Though the number of digits reduces quickly, worst-case time is O(log n), with space O(k) for visited states.
4. Two Sum
Given an array and a target, find indices of the two elements summing to the target.
Use a HashMap to store each element and its index while iterating. For each element x, look for target - x in the map — if found, return the indices.
public int[] locatePair(int[] input, int goal) {
Map<integer integer=""> indexMap = new HashMap<>();
for (int i = 0; i < input.length; i++) {
int complement = goal - input[i];
if (indexMap.containsKey(complement)) {
return new int[]{i, indexMap.get(complement)};
}
indexMap.put(input[i], i);
}
return new int[0]; // should not reach here per problem guarantees
}
</integer>
Runs in O(n) time and uses O(n) space.