Single-Row Keyboard

easy string hash map simulation

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.

Inputkeyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
Output4
0→2 (cost 2) for 'c', 2→1 (cost 1) for 'b', 1→0 (cost 1) for 'a'. Total = 2 + 1 + 1 = 4.

def 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;
}
Time: O(n) Space: O(1)