Single-Row Keyboard
Problem
There is a special keyboard with all keys in a single row, given as a string keyboard of length 26 (a permutation of the lowercase letters). The finger starts at index 0. To type a character you move the finger from its current index to that character's index, costing the absolute difference in indices, then type it (zero extra time). Return the total time to type the string word.
keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"4def calculate_time(keyboard, word):
pos = {c: i for i, c in enumerate(keyboard)}
total = 0
cur = 0
for ch in word:
total += abs(pos[ch] - cur)
cur = pos[ch]
return total
function calculateTime(keyboard, word) {
const pos = {};
for (let i = 0; i < keyboard.length; i++) pos[keyboard[i]] = i;
let total = 0, cur = 0;
for (const ch of word) {
total += Math.abs(pos[ch] - cur);
cur = pos[ch];
}
return total;
}
class Solution {
public int calculateTime(String keyboard, String word) {
int[] pos = new int[26];
for (int i = 0; i < keyboard.length(); i++) pos[keyboard.charAt(i) - 'a'] = i;
int total = 0, cur = 0;
for (char ch : word.toCharArray()) {
int p = pos[ch - 'a'];
total += Math.abs(p - cur);
cur = p;
}
return total;
}
}
int calculateTime(string keyboard, string word) {
int pos[26];
for (int i = 0; i < (int)keyboard.size(); i++) pos[keyboard[i] - 'a'] = i;
int total = 0, cur = 0;
for (char ch : word) {
int p = pos[ch - 'a'];
total += abs(p - cur);
cur = p;
}
return total;
}
Explanation
The finger only moves along one row, so the cost to type a character is just the distance between where the finger is and where that key sits. We add up those distances as we type.
First we build a lookup pos that maps each letter to its index on the keyboard, so we can find any key's position instantly. We start the finger at cur = 0 and keep a running total of 0.
For each character ch in the word, the move cost is abs(pos[ch] - cur) — the absolute gap between the finger's current index and the target key's index. We add that to total and then update cur to the key we just reached.
Example: keyboard = "abc...z", word = "cba". Finger starts at 0. To 'c' (index 2): cost |2 - 0| = 2. To 'b' (index 1): cost |1 - 2| = 1. To 'a' (index 0): cost |0 - 1| = 1. Total = 2 + 1 + 1 = 4.
We do one quick pass to build the map and one pass over the word, so the whole thing is linear and uses only a fixed-size lookup table.