Single-Row Keyboard - Problem
Imagine a futuristic keyboard where all 26 letters are arranged in a single horizontal row instead of the traditional QWERTY layout. You're a one-finger typist (like many of us on mobile phones!) and need to calculate the total time required to type a word.
Given:
- A string
keyboardof length 26 representing the custom layout (each letter appears exactly once) - A string
wordthat you want to type
Rules:
- Your finger starts at position 0 (the first key)
- To type any character, you must move your finger to that character's position
- The time to move from position
ito positionjis|i - j|
Goal: Return the minimum time needed to type the entire word.
Example: If keyboard = "abcdefghijklmnopqrstuvwxyz" and word = "cba", you'd move: 0→2 (cost 2), 2→1 (cost 1), 1→0 (cost 1) = total time of 4.
Input & Output
example_1.py — Basic Example
$
Input:
keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
›
Output:
4
💡 Note:
Starting at position 0: move to 'c' at position 2 (cost 2), then to 'b' at position 1 (cost 1), then to 'a' at position 0 (cost 1). Total: 2+1+1 = 4.
example_2.py — Custom Keyboard Layout
$
Input:
keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode"
›
Output:
73
💡 Note:
With this custom layout, characters are in different positions. We calculate the distance for each character move: l→e→e→t→c→o→d→e, summing all the absolute differences between consecutive positions.
example_3.py — Single Character
$
Input:
keyboard = "abcdefghijklmnopqrstuvwxyz", word = "z"
›
Output:
25
💡 Note:
Edge case with single character. Starting at position 0, we need to move to 'z' at position 25, so the total time is |0-25| = 25.
Constraints
-
keyboard.length == 26 -
keyboardcontains each English lowercase letter exactly once in some order -
1 ≤ word.length ≤ 104 -
word[i]is a lowercase English letter
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Place finger at starting position (index 0) on the keyboard
2
Lookup Position
Use hash table to instantly find the target character's position
3
Calculate Distance
Compute absolute difference between current and target positions
4
Move Finger
Add the distance to total time and update current position
5
Repeat
Continue for each character in the word
Key Takeaway
🎯 Key Insight: Instead of searching through the keyboard repeatedly, create a hash table once to enable instant O(1) character position lookups, reducing time complexity from O(n×26) to O(n).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code