Letter Combinations of a Phone Number
Anonymous
Here's the exact code I wrote during the interview test. As far as I know, this covered all edge-cases. public class PhoneKeyMapper{ //create a reference for phone key value mapping private Map> phoneKeyMap = getPhoneKeyMap(); public List letterCombinations(String number) { List result = new ArrayList(); char[] digits = number.toCharArray(); // convert number to character array for(int i=digits.length-1; i>=0; i--){ // for each digit-character List partialResult = new ArrayList(); // stores partial values, per iteration if(result.isEmpty()){ //when result array is empty - initially for the first digit result.addAll(phoneKeyMap.get(digits[i])); } else { partialResult.addAll(result); result.clear(); // empty results so far // for every character in phone key map for(String ch: phoneKeyMap.get(digits[i])){ // for each partialResult for(String pr: partialResult){ //create concatenated string and add to result. result.add(ch+pr); } } } } return result; } private static Map> getPhoneKeyMap(){ Map> phoneKeyMap = new HashMap(); phoneKeyMap.put('1', Arrays.asList(new String[]{})); phoneKeyMap.put('2', Arrays.asList(new String[]{"a", "b", "c"})); phoneKeyMap.put('3', Arrays.asList(new String[]{"d", "e", "f"})); ...... return phoneKeyMap; } }
Check out your Company Bowl for anonymous work chats.