Single-Row Keyboard Problem
Description
LeetCode Problem 1165.
There is a special keyboard with all keys in a single row.
Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25). Initially, your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is |i - j|.
You want to type a string word. Write a function to calculate how much time it takes to type it with one finger.
Example 1:
Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
Output: 4
Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'.
Total time = 2 + 1 + 1 = 4.
Example 2:
Input: keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode"
Output: 73
Constraints:
keyboard.length == 26keyboardcontains each English lowercase letter exactly once in some order.1 <= word.length <= 10^4word[i]is an English lowercase letter.
Solution
Approach: Position Table
Typing a letter costs the distance between the finger and that letter's key, and then the finger stays on that key. Scanning keyboard to find each letter would work, but it is simpler and faster to first record where every letter is: pos[c] is the index of letter c.
Then walk through word with the finger starting at index 0. For each letter, add |pos[c] - finger| to the total and move the finger to pos[c]. Typing the same letter twice in a row costs 0.
Complexity: O(n) time for a word of length n, and O(1) extra space for the 26 positions.
class Solution:
def calculateTime(self, keyboard: str, word: str) -> int:
pos = {c: i for i, c in enumerate(keyboard)} # letter -> its key index
ans = finger = 0
for c in word:
ans += abs(pos[c] - finger)
finger = pos[c]
return ans