Amazon OA. count family logins

question is :
given array of logins(String loginID ex 'abc')
find how many of pairs are family logins (2 logins family login if one loginID is shifting all char to the left by 1 step, or all to the right by 1 step.)

ex.
given 'abc' , 'def', 'bcd, 'bcd'
we have 2 famliy logins as pair {1, 3}, {1,4}

i didn't pass the test. but after a day, i think i should have use hashmap to record all loginID's appear frequency. then for each ID in the hashmap, we can leftShift and rightShift to find these can be found in hashmap. then add up (and multiply by this ID frequency).

in the end we devide by 2, (because we double countted each pair).

i write my code as below. can someone give your thought if this is correct.
or if anyone has better idea how to solve it. feel free to drop it in comment

'''

public int countFamilyLogins(List<String> logins){
    //big idea is to use hashmap to store all user's frequency. 
    //then for each key within the hashmap, find if we can find its left/right shift string. add up. in end /2 to get res;
    int res = 0;
    HashMap<String, Integer> hm = new HashMap<String, Integer>();

    for(int i = 0; i < logins.size(); i++){ //add the user frequency into a hashMap
        String s = logins.get(i);
        if(hm.containsKey(s)) hm.put(s, hm.get(s) + 1);
        else hm.put(s, 1);
    }

    for(String s : hm.keySet()){ //traverse thru the hashMap 
        int sNum = hm.get(s);
        String l = leftShift(s);
        String r = rightShift(s);

        if(hm.contains(l)) res += sNum * hm.get(l);  //leftShift ID found. add up
        if(hm.contains(r)) res += sNum * hm.get(r);  //rightShift ID found.
    }

    return res / 2;
}

public String leftShift(String s){
    StringBuilder sb = new StringBuilder(s);
    for(int i = 0; i < sb.size(); i++){
        char c = sb.charAt(i);
        if(c.equals('a')) sb.setCharAt(i, 'z');
        else sb.setCharAt(i, c - 1);
    }
    return sb.toString();
}
public String rightShift(String s){
    StringBuilder sb = new StringBuilder(s);
    for(int i = 0; i < sb.size(); i++){
        char c = sb.charAt(i);
        if(c.equals('z')) sb.setCharAt(i, 'a');
        else sb.setCharAt(i, c + 1);
    }
    return sb.toString();
}

'''

Comments (5)