Interview Question
Software DevelopersCountry: United States
/**
* Java Solution
* O(n) time complexity and O(1) space complexity
*/
public static void process(String input, int width) {
int currentRow = 0;
int currentCol = -1;
for (int i = 0; i < input.length(); i++) {
int next = input.charAt(i) - 'A'; //next character
/** convert next character in to 2D location (row and col) based on input width of keyboard */
int row = next / width;
int col = next % width;
/** move robot hand from currentRow, currentCol to row, col */
if (row < currentRow) {
System.out.print("U" + (currentRow - row) + ", ");
} else if (row > currentRow){
System.out.print("D" + (row - currentRow) + ", ");
}
if (col < currentCol) {
System.out.print("L" + (currentCol - col) + ", ");
} else if (col > currentCol){
System.out.print("R" + (col - currentCol) + ", ");
}
if (i < input.length() - 1) {
System.out.print("T, ");
} else {
System.out.print('T');
}
/** change currentRow and currentCol to new location */
currentRow = row;
currentCol = col;
}
}
The code below should work.
The logic is pretty simple, imagine the keyboard as a matrix. If the keyboard size is 26, it is a matrix with 1 row, 26 columns. When the keyboard size is 13, it is a matrix with 2 row and 13 columns.
All we have to now do is compute the moves from source to destination for each character.
For "Hi"
0,0 -> 0,8 (move by 8 columns -> R8)
0,8 -> 0,9 (move by 1 column -> R1)
- kirubakaran.d November 08, 2017