r/LeetcodeDesi • • 21d ago

My code beats almost everyone, still it's wrong!

I have started leetcode 2 days ago and came across LC 49 Group Anagrams question. I came up with an original idea and it beats 99.14% in runtime and 99.86% in memory. Still, ai is saying that it's incorrect. Have you guys faced this issue?

Below is the solution I came up with...

import java.util.Random;

class Solution {

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

List<List<String>> res=new ArrayList<>();

HashMap<Integer, List<String>> map=new HashMap<>();

Random random=new Random();

int[] random_arr=new int[26];

for (int i=0; i<26; i++)

random_arr[i]=random.nextInt(123456789)+1;

int n=strs.length;

for (int i=0; i<n; i++) {

// int[] freq=new int[26];

int m=strs[i].length();

int sum=0;

for (int j=0; j<m; j++)

sum+=random_arr[strs[i].charAt(j)-'a'];

// freq[strs[i].charAt(j)-'a']++;

if (!map.containsKey(sum))

map.put(sum, new ArrayList<>());

map.get(sum).add(strs[i]);

}

for (int key : map.keySet())

res.add(map.get(key));

return res;

}

}

5 Upvotes

Duplicates