3ms Java Solution

  • 0

    similar idea to lots of posts on the forum, use String as key in the map and a list to hold all the strings of the same group,
    for every string, transform it using the offset and add it to the map accordingly.

    public List<List<String>> groupStrings(String[] strings) {
            List<List<String>> result = new ArrayList<>();
            Map<String, List<String>> map = new HashMap<> ();
            for (String str : strings) {
                String key = getKey(str);
                if (!map.containsKey(key)) {
                    map.put(key, new ArrayList<>());    
            for (String key : map.keySet()) {
            return result;
        private String getKey(String word) {
            StringBuilder sb = new StringBuilder();
            if (word.isEmpty())
                return sb.toString();
            int offset = word.charAt(0) - 'a';
            for (int i = 0; i < word.length(); i++) {
                sb.append((char)((word.charAt(i) + 26 - offset) % 26));
            return sb.toString();

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.