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 INPUT Keyboard Layout (single row): a 0 b 1 c 2 d 3 e 4 f 5 g 6 h 7 i 8 j 9 k 10 ... (continues to z at index 25) Finger starts at index 0 F Word to type: c b a Hash Map (char --> index): 'a': 0 'b': 1 'c': 2 ... (all 26 chars mapped) keyboard = "abcdef...xyz" word = "cba" ALGORITHM STEPS 1 Build Hash Map Map each char to its index 2 Type 'c': pos 0 --> 2 Distance: |2-0| = 2 3 Type 'b': pos 2 --> 1 Distance: |1-2| = 1 4 Type 'a': pos 1 --> 0 Distance: |0-1| = 1 Finger Movement Trace: a 0 b 1 c 2 d 3 0-->2 (+2) 2-->1 (+1) 1-->0 (+1) FINAL RESULT Total Time Calculation: Move to 'c': +2 Move to 'b': +1 Move to 'a': +1 Total: 4 Output: 4 OK - Time units to type "cba" Time: O(n) | Space: O(26) = O(1) n = length of word Key Insight: Using a Hash Map provides O(1) lookup time for each character's position on the keyboard. The total time is the sum of absolute differences between consecutive character positions. Formula: time = sum of |pos[word[i]] - pos[word[i-1]]| for all i, starting from finger position 0. TutorialsPoint - Single-Row Keyboard | Hash Map Optimization Approach
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