Single-Row Keyboard - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
Output: 4
💡 Note: Start at 0. Move to 'c' at position 2: |0-2| = 2. Move to 'b' at position 1: |2-1| = 1. Move to 'a' at position 0: |1-0| = 1. Total: 2+1+1 = 4
Example 2 — Custom Layout
$ Input: keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode"
Output: 73
💡 Note: With custom keyboard layout, characters are at different positions. Calculate distance for each character move.
Example 3 — Single Character
$ Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "z"
Output: 25
💡 Note: Start at position 0, move to 'z' at position 25: |0-25| = 25

Constraints

  • keyboard.length == 26
  • keyboard contains each English lowercase letter exactly once
  • 1 ≤ word.length ≤ 104
  • word[i] is an English lowercase letter

Visualization

Tap to expand
Single Row Keyboard: Calculate Typing TimeKeyboard Layout:abcdefg0123456... (h-z)Word to type: "cba"Move 2Move 1Move 1Total Movement Time2 + 1 + 1 = 4
Understanding the Visualization
1
Input
Keyboard layout and word to type
2
Process
Calculate finger movement distances
3
Output
Total time for all movements
Key Takeaway
🎯 Key Insight: Pre-mapping character positions eliminates the need for repeated searches, making the solution efficient.
Asked in
Google 12 Amazon 8 Microsoft 6
35.7K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen