Skip to content

1165. Single-Row Keyboard 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 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) {
    int ans = 0;
    int prevIndex = 0;
    vector<int> letterToIndex(26);

    for (int i = 0; i < keyboard.length(); ++i)
      letterToIndex[keyboard[i] - 'a'] = i;

    for (const char c : word) {
      const int currIndex = letterToIndex[c - 'a'];
      ans += abs(currIndex - prevIndex);
      prevIndex = currIndex;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int calculateTime(String keyboard, String word) {
    int ans = 0;
    int prevIndex = 0;
    int[] letterToIndex = new int[26];

    for (int i = 0; i < keyboard.length(); ++i)
      letterToIndex[keyboard.charAt(i) - 'a'] = i;

    for (final char c : word.toCharArray()) {
      final int currIndex = letterToIndex[c - 'a'];
      ans += Math.abs(currIndex - prevIndex);
      prevIndex = currIndex;
    }

    return ans;
  }
}
1
2
3
4
5
6
class Solution:
  def calculateTime(self, keyboard: str, word: str) -> int:
    letterToIndex = {c: i for i, c in enumerate(keyboard)}
    return (letterToIndex[word[0]] +
            sum(abs(letterToIndex[a] - letterToIndex[b])
            for a, b in itertools.pairwise(word)))