 # Sum and product of string

#1

I took sum and product of every string then performed modulo 10^9+7 on total of “sum” and “product”.If total is present in hashmap i added index of that string to the arraylist else make a new entry in hashmap.
This method passed all testcases but i’m still not sure.Can two string exist which are not anagram and have same sum and product value.

HashMap<Long,ArrayList> map=new HashMap<Long,ArrayList>;
ArrayList<ArrayList> res=new ArrayList<ArrayList>();
if(A.length()==0)
return res;

``````    long sum,product;

for(int i=0;i<A.size();i++){
String s=A.get(i);
sum=0; product=1;
for(int j=0;j<s.length();j++){
sum+=(long)(s.charAt(j)-96);
product*=(long)(s.charAt(j)-96);

sum%=(1000000007);
product%=(1000000007);
}
long total=(sum+product)%1000000007;

ArrayList<Integer> al=null;
if(!map.containsKey(total))
al=new ArrayList<Integer>();
else
al=map.get(total);

map.put(total,al);
}

for(Map.Entry<Long,ArrayList<Integer>> entry:map.entrySet()){
}

return res;``````

#2

Yes, according to your code. You add and multiply 1 for ‘a’, 2 for ‘b’, 3 for ‘c’… so on…
Consider two strings with same product, “hh”(8*8=64) and “bbbbbb”(2^6=64), but the sum for the latter is less (16>12) so add 4 ‘a’ to that last string.
so, “hh” and “bbbbbbaaaa” have same sum and product.
I think without subtracting 96 you’re better off.

#3

or else first create a map with each character mapped with a prime number then you won’t get conflicts.