titan2400

Group Anagrams - LeetCode

Oct 27th, 2025 (edited)
629
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | Source Code | 0 0
  1. // Group Anagrams - https://leetcode.com/problems/group-anagrams/
  2.  
  3. class Solution {
  4.  
  5.     // Using HashMap to build dictionary
  6.     // Time Complexity: O(n * klogk)
  7.     //  where k is the length of string
  8.     // Space Complexity: O(n * k)
  9.  
  10.     // Key Clarifications
  11.     // - Do we need special handling for empty strings
  12.     // - Can we assume that input strings are all lowercase
  13.     // public List<List<String>> groupAnagrams(String[] strs) {
  14.  
  15.     //     Map<String, List<String>> map = new HashMap<>();
  16.  
  17.     //     for(int i = 0; i < strs.length; i++) {
  18.     //         char[] charArray = strs[i].toCharArray();
  19.     //         Arrays.sort(charArray);
  20.     //         String sorted = new String(charArray);
  21.  
  22.     //         List<String> anagrams = map.getOrDefault(sorted, new ArrayList<>());
  23.     //         anagrams.add(strs[i]);
  24.     //         map.put(sorted, anagrams);
  25.     //     }
  26.  
  27.     //     List<List<String>> result = new ArrayList<>();
  28.     //     for(List<String> anagrams: map.values()) {
  29.     //         result.add(anagrams);
  30.     //     }
  31.  
  32.     //     return result;
  33.     // }
  34.  
  35.     // Same as above but compact code
  36.     public List<List<String>> groupAnagrams(String[] strs) {
  37.  
  38.         Map<String, List<String>> map = new HashMap<>();
  39.         for(int i = 0; i < strs.length; i++) {
  40.             char[] charArray = strs[i].toCharArray();
  41.             Arrays.sort(charArray);
  42.             String sorted = new String(charArray);
  43.             map.putIfAbsent(sorted, new ArrayList<>());
  44.             map.get(sorted).add(strs[i]);
  45.         }
  46.  
  47.         return new ArrayList<>(map.values());
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment