1165. Single-Row Keyboard
Last updated
Last updated
/**
* Time complexity : O(n). Where n is the length of word, since we need to
* traverse the word. An additional constant of O(26) = O(1) is needed
* to iterate through keyboard.
* Space complexity : O(1). The algorithm requires constant space to store
* indices for 26 letters.
*/
class Solution {
public int calculateTime(String keyboard, String word) {
int[] keyIndices = new int[26];
for(int i = 0; i < keyboard.length(); i++) {
keyIndices[keyboard.charAt(i)-'a'] = i;
}
int cost = 0, prev = 0;
for(char ch: word.toCharArray()) {
int index = keyIndices[ch-'a'];
cost += Math.abs(index-prev);
prev = index;
}
return cost;
}
}