SingleRow Keyboard
We need to calculate the total time taken to type a given word, considering a specific layout of the keyboard. We will determine the time by calculating the absolute difference between the indices of consecutive characters in the word.


Explanation
 We first create a dictionary
index_map
that maps each character in the keyboard to its index. This helps us quickly find the index of a character in the word.  We initialize two variables:
time_taken
to keep track of the total time taken andcurrent_index
to keep track of the current position of the finger.  We loop through each character in the word and calculate the absolute difference between the current index and the next index of the character in the word. This difference represents the time taken to move the finger from one character to the next.
 We update
current_index
to the next index for the following iteration.  Finally, we return the total time taken.
By using the dictionary to store the index of each character, we ensure that the lookup time is constant, leading to an efficient solution.
title: SingleRow Keyboard excerpt: Constant space solution for SingleRow Keyboard problem. tags: linearscan relativepositionofelement
First Attempt
The first attempt only passes the first test case:


The first index is 0, this must be changed in every iteration to the position of the character we just typed.
Working Solution


Time Complexity: O(N * K)
Where N is the word size and K is the keyboard size. Keyboard length is 26, so the runtime is linear.
Space Complexity: O(1).
If we cannot use the language specific method like index, we can use a hash table.


Time: O(N), where N is the size of the word. Space: O(1), because we only need to store 26 and this does not increase when the input size increases.