669. Single-Row Keyboard

There is a special keyboard with all keys arranged in a single row.

Given a string keyboard of length 26 representing the layout of the keyboard (indexed from 0 to 25). Initially, your finger starts at index 0. To type a character, you must move your finger to the index of the desired character. The time taken to move from index i to index j is |i - j|.

You want to type a string word. Write a function to compute the total time required to type the word using one finger.

Example 1:

Input: keyboard = "zyxwvutsrqponmlkjihgfedcba", word = "dog"

Output: 41  

Explanation:

  • Move from index 0 → 22 ('d') → Cost = 22
  • Move from index 22 → 11 ('o') → Cost = 11
  • Move from index 11 → 19 ('g') → Cost = 8
  • Total time = 22 + 11 + 8 = 41

Example 2:

Input: keyboard = "qwertyuiopasdfghjklzxcvbnm", word = "apple"

Output: 36  

Explanation:

  • Move from index 0 → 10 ('a') → Cost = 10
  • Move from index 10 → 8 ('p') → Cost = 2
  • Move from index 8 → 8 ('p') → Cost = 0
  • Move from index 8 → 18 ('l') → Cost = 10
  • Move from index 18 → 4 ('e') → Cost = 14
  • Total time = 10 + 2 + 0 + 10 + 14 = 36

Now Your Turn!

Pick the correct output for the given input

Input: keyboard = "mnbvcxzlkjhgfdsapoiuytrewq", word = "chat"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • keyboard.length == 26
  • keyboard contains each English lowercase letter exactly once in some order.
  • 1 <= word.length <= 10⁴
  • word[i] is an English lowercase letter.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int calculateTime(string keyboard, string word) {
// Your code goes here
}
};
Test Case

Input:

Keyboard
Word