Problem Description
A special keyboard has all keys arranged in a single row. Given a string called keyboard of length 26 representing the keyboard layout (each letter appears exactly once) and a word to type, calculate the total time needed to type that word. The time to move from one key to another is defined as the absolute difference between their indices. Initially, your finger is at index 0.
Key Insights
- Create a mapping (hash table/dictionary) from each character to its index on the keyboard for O(1) lookups.
- The cost to type each character is the absolute difference between the current position and the target character's position on the keyboard.
- Start from index 0 and sum up the distances moved for each successive character in the word.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the word. Space Complexity: O(1) (constant space for a mapping of 26 characters).
Solution
We solve the problem by first building a dictionary that maps each character in the keyboard layout to its corresponding index. We then initialize a variable to track the current finger position (starting at 0). For each character in the word, we look up its index, calculate the absolute difference from the current position, add that distance to the total time, and update the current position. This approach uses a single pass over the word with constant time lookups, ensuring an efficient solution.