1 minute read

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 abs(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.

URL: https://leetcode.com/problems/single-row-keyboard/

My solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int calculateTime(String keyboard, String word) {
        //first map each letter to an index
        Map<Character,Integer> map = new HashMap<>();
        
        for (int i = 0; i < keyboard.length(); i++) {
            char ltr = keyboard.charAt(i);
            map.put(ltr,i);
        }
        
        int time = map.get(word.charAt(0));
        
        for (int i = 1; i < word.length(); i++) {
            time += Math.abs(map.get(word.charAt(i)) - map.get(word.charAt(i-1)));
        }
        return time;
        
    }
}

Explanation:

Lines 6-9 create a map with the letters as keys and the indices as values

Line 11 initializes the time with the first value in the array, the time it takes to hit the first key from initial position

Line 13 is a loop that iterates through the rest of the array to calculate the travel times

line 14 adds the total time to the diffence in map values between the current letter and previous letter. This difference represents the travel time to the current key and is added to the total time.

Line 16 returns the total time