Skip to content

Comments

Adding all the solutions#2269

Open
subbu4061 wants to merge 1 commit intosuper30admin:masterfrom
subbu4061:master
Open

Adding all the solutions#2269
subbu4061 wants to merge 1 commit intosuper30admin:masterfrom
subbu4061:master

Conversation

@subbu4061
Copy link

No description provided.

@super30admin
Copy link
Owner

Strengths:

  • The solution correctly implements the prime multiplication approach to group anagrams.
  • The code is well-commented and easy to understand.
  • Edge cases are handled appropriately.

Areas for Improvement:

  • The edge cases (empty input and single element) are redundant because the main logic already handles them. You can remove these checks to simplify the code.
  • Consider using a double for the hash product instead of BigInteger for better performance, as the maximum string length is 100. The product of 100 primes (each up to 101) will be within the range of a double without losing precision for grouping purposes. However, if you are concerned about precision, BigInteger is safe but slower.
  • Instead of checking if the key exists and then getting the list, you can use map.computeIfAbsent(key, k -> new ArrayList<>()).add(curr) to make the code more concise.

Example of improved code:

import java.util.*;

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<Double, List<String>> map = new HashMap<>();
        int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};
        for (String curr : strs) {
            double product = 1.0;
            for (char c : curr.toCharArray()) {
                product *= primes[c - 'a'];
            }
            map.computeIfAbsent(product, k -> new ArrayList<>()).add(curr);
        }
        return new ArrayList<>(map.values());
    }
}

Note: The above code uses double, which is efficient and sufficient for the given constraints.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants