[Geeks for Geeks] A Special Keyboard

A Special Keyboard

Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string S1 of length 26. S1 is 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 |j-i|, where || denotes absolute value.Find the time taken to type the string S2 with the given keyboard layout.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int findTime(string S1, string S2) {
unordered_map<char, int> mp;
for(int i = 0; i < 26; i++) mp[S1[i]] = i;
int res = 0;
char prv = S1[0];
for(auto& ch : S2) {
res += abs(mp[ch] - mp[prv]);
prv = ch;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/26/PS/GeeksforGeeks/a-special-keyboard/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.