// Top 50 String and Array Manipulation Problems Using Java Collections and Streams
import java.util.*;
import java.util.function.Function;
import java.util.stream.*;
public class JavaCodingProblems {
// 1. Count frequency of characters in a string
public static Map<Character, Long> charFrequency(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
}
// 2. First non-repeating character
public static Character firstNonRepeatingChar(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, LinkedHashMap::new,
Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst().orElse(null);
}
// 3. Check if two strings are anagrams
public static boolean areAnagrams(String str1, String str2) {
return str1.chars().sorted().boxed().collect(Collectors.toList())
.equals(str2.chars().sorted().boxed().collect(Collectors.toList()));
}
// 4. Reverse each word in a string
public static String reverseWords(String str) {
return Arrays.stream(str.split(" "))
.map(w -> new StringBuilder(w).reverse().toString())
.collect(Collectors.joining(" "));
}
// 5. Remove duplicate characters
public static String removeDuplicateChars(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.distinct()
.map(String::valueOf)
.collect(Collectors.joining());
}
// 6. Find duplicate characters
public static Set<Character> duplicateChars(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
// 7. Check if string is a palindrome
public static boolean isPalindrome(String str) {
return IntStream.range(0, str.length() / 2)
.allMatch(i -> str.charAt(i) == str.charAt(str.length() - 1 - i));
}
// 8. Longest word in sentence
public static String longestWord(String sentence) {
return Arrays.stream(sentence.split(" "))
.max(Comparator.comparingInt(String::length)).orElse("");
}
// 9. Most frequent character
public static Character mostFrequentChar(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.get().getKey();
}
// 10. Check string rotation
public static boolean isRotation(String str1, String str2) {
return str1.length() == str2.length() && (str1 + str1).contains(str2);
}
// 11. Remove duplicates from array
public static Integer[] removeDuplicates(Integer[] arr) {
return Arrays.stream(arr).distinct().toArray(Integer[]::new);
}
// 12. Max and min in array
public static int[] maxMin(int[] arr) {
return new int[] { Arrays.stream(arr).min().orElseThrow(),
Arrays.stream(arr).max().orElseThrow() };
}
// 13. Sort array descending
public static int[] sortDescending(int[] arr) {
return
Arrays.stream(arr).boxed().sorted(Comparator.reverseOrder()).mapToInt(Integer::intValue)
.toArray();
}
// 14. Find duplicates in array
public static Set<Integer> findDuplicates(int[] arr) {
return Arrays.stream(arr).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
// 15. Find common elements
public static List<Integer> commonElements(int[] arr1, int[] arr2) {
Set<Integer> set1 = Arrays.stream(arr1).boxed().collect(Collectors.toSet());
return
Arrays.stream(arr2).filter(set1::contains).boxed().collect(Collectors.toList());
}
// 16. Find missing number 1 to N
public static int findMissing(int[] arr, int n) {
int total = IntStream.rangeClosed(1, n).sum();
int sum = Arrays.stream(arr).sum();
return total - sum;
}
// 17. Second highest number
public static int secondHighest(int[] arr) {
return Arrays.stream(arr).boxed().distinct()
.sorted(Comparator.reverseOrder()).skip(1).findFirst().orElseThrow();
}
// 18. Group even and odd
public static Map<Boolean, List<Integer>> groupEvenOdd(int[] arr) {
return Arrays.stream(arr).boxed().collect(Collectors.partitioningBy(n -> n % 2
== 0));
}
// 19. Count frequencies
public static Map<Integer, Long> countFrequencies(int[] arr) {
return Arrays.stream(arr).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
// 20. Find majority element
public static Optional<Integer> majorityElement(int[] arr) {
int n = arr.length;
return Arrays.stream(arr).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > n / 2)
.map(Map.Entry::getKey).findFirst();
}
// 21. Find all pairs with a given sum
public static List<List<Integer>> findPairsWithSum(int[] arr, int target) {
Set<Integer> seen = new HashSet<>();
List<List<Integer>> result = new ArrayList<>();
for (int num : arr) {
int complement = target - num;
if (seen.contains(complement)) {
result.add(Arrays.asList(complement, num));
}
seen.add(num);
}
return result;
}
// 22. Rotate array to the right by k steps
public static int[] rotateRight(int[] arr, int k) {
int n = arr.length;
return IntStream.range(0, n)
.map(i -> arr[(n - k + i) % n])
.toArray();
}
// 23. Check if array contains a number
public static boolean contains(int[] arr, int key) {
return Arrays.stream(arr).anyMatch(x -> x == key);
}
// 24. Merge two arrays and remove duplicates
public static int[] mergeUnique(int[] arr1, int[] arr2) {
return Stream.concat(Arrays.stream(arr1).boxed(), Arrays.stream(arr2).boxed())
.distinct().mapToInt(i -> i).toArray();
}
// 25. Intersect two arrays
public static int[] intersectArrays(int[] arr1, int[] arr2) {
Map<Integer, Long> map = Arrays.stream(arr1).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return Arrays.stream(arr2).filter(n -> map.getOrDefault(n, 0L) > 0 && map.put(n,
map.get(n) - 1) >= 1)
.toArray();
}
// 26. Find kth smallest element
public static int kthSmallest(int[] arr, int k) {
return Arrays.stream(arr).sorted().skip(k - 1).findFirst().orElseThrow();
}
// 27. Find all palindromic substrings
public static List<String> palindromicSubstrings(String str) {
Set<String> result = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
String sub = str.substring(i, j);
if (isPalindrome(sub)) result.add(sub);
}
}
return new ArrayList<>(result);
}
// 28. Find longest palindromic substring
public static String longestPalindrome(String str) {
String res = "";
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
String sub = str.substring(i, j);
if (isPalindrome(sub) && sub.length() > res.length()) res = sub;
}
}
return res;
}
// 29. Convert string to title case
public static String toTitleCase(String str) {
return Arrays.stream(str.split(" "))
.map(s -> s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase())
.collect(Collectors.joining(" "));
}
// 30. Replace all spaces with underscore
public static String replaceSpaces(String str) {
return str.replace(" ", "_");
}
// 31. Find all permutations of a string (recursive approach)
public static Set<String> permutations(String str) {
if (str.length() == 0) return Set.of("");
Set<String> result = new HashSet<>();
char ch = str.charAt(0);
for (String perm : permutations(str.substring(1))) {
for (int i = 0; i <= perm.length(); i++) {
result.add(perm.substring(0, i) + ch + perm.substring(i));
}
}
return result;
}
// 32. Group words by anagram
public static Collection<List<String>> groupAnagrams(List<String> words) {
return words.stream().collect(Collectors.groupingBy(
w -> w.chars().sorted().collect(StringBuilder::new,
StringBuilder::appendCodePoint, StringBuilder::append).toString()
)).values();
}
// 33. Remove all vowels from string
public static String removeVowels(String str) {
return str.replaceAll("[aeiouAEIOU]", "");
}
// 34. Convert string to camel case
public static String toCamelCase(String str) {
String[] parts = str.split(" ");
StringBuilder sb = new StringBuilder(parts[0].toLowerCase());
for (int i = 1; i < parts.length; i++) {
sb.append(parts[i].substring(0,
1).toUpperCase()).append(parts[i].substring(1).toLowerCase());
}
return sb.toString();
}
// 35. Find max occurring word in a sentence
public static String maxOccurringWord(String str) {
return Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream().max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey).orElse("");
}
// 36. Capitalize alternate characters
public static String capitalizeAlternate(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
sb.append(i % 2 == 0 ? Character.toUpperCase(str.charAt(i)) :
str.charAt(i));
}
return sb.toString();
}
// 37. Count digits, letters and special characters
public static Map<String, Long> countTypes(String str) {
return str.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(c -> {
if (Character.isDigit(c)) return "Digits";
else if (Character.isLetter(c)) return "Letters";
else return "Specials";
}, Collectors.counting()));
}
// 38. Reverse string without affecting special characters
public static String reversePreserveSpecial(String str) {
char[] chars = str.toCharArray();
int i = 0, j = chars.length - 1;
while (i < j) {
if (!Character.isLetter(chars[i])) i++;
else if (!Character.isLetter(chars[j])) j--;
else {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
i++;
j--;
}
}
return new String(chars);
}
// 39. Encode string with run-length encoding
public static String runLengthEncode(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
int count = 1;
while (i + 1 < str.length() && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
sb.append(str.charAt(i)).append(count);
}
return sb.toString();
}
// 40. Decode run-length encoded string
public static String runLengthDecode(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i += 2) {
char ch = str.charAt(i);
int count = str.charAt(i + 1) - '0';
sb.append(String.valueOf(ch).repeat(count));
}
return sb.toString();
}
}
}