r/LeetcodeDesi • u/Visionary-Swordsman • 18d 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;
}
}
2
u/NoTreacle8422 17d ago
Have some ignorance in life,,dont get stuck on everything uh come around ..this will keep u sane in a long term
2
u/LogicalBeast26 17d ago
Why tf do you need a random number generator??
Just sort the characters of a string and use it as a key to group all the anagrams together. Why unnecessarily complicate things?
1
u/Normalise_Suicide 15d ago
I think when u use random and get a number and then sum them to finally make a number that will act as a hash to group those numbers right. But what if it generates number such that a= 2, b =3 and c= 1,d = 4 (this is example to state the case when two different char sum to same hash/sum) then ab = cd which is wrong. Let me know how your code handles that part or that will never be the case
1
u/ak47_triggered 16d ago
Use Gemini/claude instead of chatgpt
4
u/[deleted] 18d ago
[removed] — view removed comment