Similar Problems

Similar Problems not available

Single Row Keyboard - Leetcode Solution

Companies:

LeetCode:  Single Row Keyboard Leetcode Solution

Difficulty: Easy

Topics: string hash-table  

Single Row Keyboard is a problem on LeetCode that asks you to find the time it takes for a given string to be typed on a keyboard that has only one row of keys.

The problem can be solved using a hash map to store the location of each character on the keyboard. The time complexity of this solution is O(n), where n is the length of the input string.

Here are the steps to solve the problem:

  1. Create a hashmap to store the location of each character on the keyboard. Each character is mapped to its index on the keyboard.

  2. Initialize the time counter to 0.

  3. Iterate through the input string one character at a time.

  4. For each character, calculate its distance from the previous character by subtracting the index of the previous character from the index of the current character.

  5. Add the distance to the time counter.

  6. Return the total time.

Here is the Python code that implements this algorithm:

class Solution:
    def calculateTime(self, keyboard: str, word: str) -> int:
        key_pos = {}
        for i, c in enumerate(keyboard):
            key_pos[c] = i
        
        time = 0
        prev_pos = 0
        for c in word:
            curr_pos = key_pos[c]
            time += abs(curr_pos - prev_pos)
            prev_pos = curr_pos
        
        return time

In this code, key_pos is the hash map that maps each character to its index on the keyboard. The variable time is the time counter that is initialized to 0. The prev_pos variable is the index of the previous character initialized to 0.

We iterate through the input string one character at a time. For each character, we calculate its distance from the previous character by subtracting the index of the previous character from the index of the current character. We add the distance to the time counter and update the prev_pos variable to be the index of the current character.

Finally, we return the total time.

Single Row Keyboard Solution Code

1