Saturday, 16 Oct 2021

# Calculate time required to type a word using given single-row keyboard

Calculate time required to type a word using given single-row keyboard
Given a string keyboardLayout of size 26 representing the sequence of characters present in a single row of a keyboard and a string word, the task is to calculate the total time taken to type the word, starting from the 0th key, if moving to adjacent keys requires unit time.
Examples:

Input: keyboardLayout = “abcdefghijklmnopqrstuvwxyz”, word = “dog”Output: 22Explanation:Pressing the key ‘d’ requires 3 units of time ( i.e. ‘a’ -> ‘b’ -> ‘c’ -> ‘d’)Pressing the key ‘o’ requires 11 units of time ( i.e. ‘d’ -> ‘e’ -> ‘f’ -> ‘g’ -> ‘h’ -> ‘i’ -> ‘j’ -> ‘k’ -> ‘l’ -> ‘m’ -> ‘n’ -> ‘o’)Pressing the key ‘g’ requires 8 units of time ( i.e. ‘o’ -> ‘n’ -> ‘m’ -> ‘l’ -> ‘k’ -> ‘j’ -> ‘i’ -> ‘h’ -> ‘g’)Therefore, the total time taken = 3 + 11 + 8 = 22.
Input: keyboardLayout = “abcdefghijklmnopqrstuvwxyz”, word = “abcdefghijklmnopqrstuvwxyz”Output: 35

Approach: Follow the steps below to solve the problem:Initialize a vector, say pos, to store the position of all the characters.
Initialize two variables, say last, to store the last updated index, and result, to store the total time taken to type the word.
Iterate over the characters of the string word:
Initialize two variables, say destination, to store the index of the next character required to be typed, and distance, to store the distance of that index from the current index.
Add the value of distance to result.
Update the last to destination.

After completing the above operations, print the value of result.
Below is the implementation of the above approach:

C++

#include
using namespace std;

int timeTakenToType(string& keyboardLayout,
string& word)
{

vector pos(26);

for (int i = 0; i < 26; ++i) {                     char ch = keyboardLayout[i];         pos[ch - 'a'] = i;     }             int last = 0;             int result = 0;             for (int i = 0; i < (int)word.size(); ++i) {         char ch = word[i];                     int destination = pos[ch - 'a'];                              int distance = abs(destination - last);                     result += distance;                     last = destination;     }             cout