0% found this document useful (0 votes)
39 views8 pages

Java8 Problems Solutions All 50

The document contains a collection of Java methods for various string and array manipulations, including reversing strings, checking for palindromes, finding anagrams, and more. Each method is implemented with clear logic and utilizes Java's built-in data structures and libraries. The methods cover a wide range of functionality, from basic operations to more complex algorithms like finding the Kth largest element and top K frequent elements.

Uploaded by

akash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views8 pages

Java8 Problems Solutions All 50

The document contains a collection of Java methods for various string and array manipulations, including reversing strings, checking for palindromes, finding anagrams, and more. Each method is implemented with clear logic and utilizes Java's built-in data structures and libraries. The methods cover a wide range of functionality, from basic operations to more complex algorithms like finding the Kth largest element and top K frequent elements.

Uploaded by

akash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1.

Reverse a String

public String reverseString(String s) {


return new StringBuilder(s).reverse().toString();
}

2. Check for Palindrome

public boolean isPalindrome(String s) {


String clean = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
return new StringBuilder(clean).reverse().toString().equals(clean);
}

3. Find Anagrams

public boolean areAnagrams(String s1, String s2) {


char[] a1 = s1.toCharArray();
char[] a2 = s2.toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
return Arrays.equals(a1, a2);
}

4. First Non-Repeating Character

public char firstNonRepeatingChar(String s) {


Map<Character, Integer> map = new LinkedHashMap<>();
for (char c : s.toCharArray()) map.put(c, map.getOrDefault(c, 0) + 1);
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) return entry.getKey();
}
return '_';
}

5. String to Integer (atoi)

public int myAtoi(String s) {


s = s.trim();
if (s.isEmpty()) return 0;
int sign = 1, i = 0, result = 0;
if (s.charAt(0) == '-' || s.charAt(0) == '+') sign = s.charAt(i++) == '-' ? -1 : 1;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
int digit = s.charAt(i++) - '0';
if (result > (Integer.MAX_VALUE - digit) / 10) return sign == 1 ?
Integer.MAX_VALUE : Integer.MIN_VALUE;
result = result * 10 + digit;
}
return result * sign;
}
6. Longest Substring Without Repeating Characters

public int lengthOfLongestSubstring(String s) {


Map<Character, Integer> map = new HashMap<>();
int maxLength = 0;
for (int start = 0, end = 0; end < s.length(); end++) {
if (map.containsKey(s.charAt(end))) {
start = Math.max(map.get(s.charAt(end)) + 1, start);
}
map.put(s.charAt(end), end);
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}

7. Reverse Words in a String

public String reverseWords(String s) {


return Arrays.stream(s.trim().split("\s+"))
.collect(Collectors.collectingAndThen(Collectors.toList(), lst -> {
Collections.reverse(lst);
return String.join(" ", lst);
}));
}

8. Count Occurrences of Characters

public Map<Character, Long> countCharOccurrences(String str) {


return str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
}

9. Remove Duplicates from String

public String removeDuplicates(String str) {


return str.chars()
.distinct()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
}

10. Replace Substring

public String replaceSubstring(String str, String target, String replacement) {


return str.replace(target, replacement);
}
11. String Compression

public String compressString(String str) {


StringBuilder sb = new StringBuilder();
int count = 1;
for (int i = 1; i <= str.length(); i++) {
if (i == str.length() || str.charAt(i) != str.charAt(i - 1)) {
sb.append(str.charAt(i - 1)).append(count);
count = 1;
} else {
count++;
}
}
return sb.toString();
}

12. Check if String Contains Substring

public boolean containsSubstring(String str, String sub) {


return str.contains(sub);
}

13. Split String by Delimiter

public String[] splitByDelimiter(String str, String delimiter) {


return str.split(Pattern.quote(delimiter));
}

14. Join Strings

public String joinStrings(List<String> list, String delimiter) {


return String.join(delimiter, list);
}

15. Sort Characters in String

public String sortCharacters(String str) {


return str.chars()
.sorted()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
}

16. Find All Substrings

public List<String> allSubstrings(String str) {


List<String> substrings = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
substrings.add(str.substring(i, j));
}
}
return substrings;
}

17. Group Anagrams

public List<List<String>> groupAnagrams(String[] strs) {


return new ArrayList<>(Arrays.stream(strs)
.collect(Collectors.groupingBy(s -> {
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
})).values());
}

18. Valid Parentheses

public boolean isValid(String s) {


Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') stack.push(')');
else if (c == '{') stack.push('}');
else if (c == '[') stack.push(']');
else if (stack.isEmpty() || stack.pop() != c) return false;
}
return stack.isEmpty();
}

19. Longest Common Prefix

public String longestCommonPrefix(String[] strs) {


if (strs == null || 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;
}

20. Implement strStr()

public int strStr(String haystack, String needle) {


return haystack.indexOf(needle);
}
21. Integer to Roman

public String intToRoman(int num) {


int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V",
"IV", "I"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length && num > 0; i++) {
while (num >= values[i]) {
num -= values[i];
sb.append(symbols[i]);
}
}
return sb.toString();
}

22. Roman to Integer

public int romanToInt(String s) {


Map<Character, Integer> map = Map.of('I', 1, 'V', 5, 'X', 10, 'L', 50,
'C', 100, 'D', 500, 'M', 1000);
int total = 0;
for (int i = 0; i < s.length(); i++) {
int val = map.get(s.charAt(i));
if (i + 1 < s.length() && val < map.get(s.charAt(i + 1))) {
total -= val;
} else {
total += val;
}
}
return total;
}

23. Array Rotation

public void rotate(int[] nums, int k) {


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;
}
}

24. Find the Missing Number


public int missingNumber(int[] nums) {
int n = nums.length;
int expectedSum = n * (n + 1) / 2;
int actualSum = Arrays.stream(nums).sum();
return expectedSum - actualSum;
}

25. Find the Duplicate Number

public int findDuplicate(int[] nums) {


Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (!seen.add(num)) return num;
}
return -1;
}

26. Two Sum

public 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];
}

27. Three Sum

public List<List<Integer>> threeSum(int[] nums) {


Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++; right--;
} else if (sum < 0) left++;
else right--;
}
}
return res;
}

28. Maximum Subarray

public int maxSubArray(int[] nums) {


int max = nums[0], curr = nums[0];
for (int i = 1; i < nums.length; i++) {
curr = Math.max(nums[i], curr + nums[i]);
max = Math.max(max, curr);
}
return max;
}

29. Merge Sorted Arrays

public int[] mergeSortedArrays(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;
}

30. Intersection of Two Arrays

public int[] intersection(int[] nums1, int[] nums2) {


Set<Integer> set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
Set<Integer> set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
set1.retainAll(set2);
return set1.stream().mapToInt(Integer::intValue).toArray();
}

31. Remove Element

public int removeElement(int[] nums, int val) {


int k = 0;
for (int num : nums) {
if (num != val) nums[k++] = num;
}
return k;
}

32. Move Zeroes

public void moveZeroes(int[] nums) {


int index = 0;
for (int num : nums) if (num != 0) nums[index++] = num;
while (index < nums.length) nums[index++] = 0;
}

33. Sort an Array (Bubble Sort Example)

public void bubbleSort(int[] arr) {


for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

34. Find the Kth Largest Element

public int findKthLargest(int[] nums, int k) {


PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : nums) {
minHeap.offer(num);
if (minHeap.size() > k) minHeap.poll();
}
return minHeap.peek();
}

35. Top K Frequent Elements

public List<Integer> topKFrequent(int[] nums, int k) {


Map<Integer, Long> freqMap = Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return freqMap.entrySet().stream()
.sorted(Map.Entry.<Integer, Long>comparingByValue().reversed())
.limit(k)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}

You might also like