Similar Problems
Similar Problems not available
Minimum Number Of Keypresses - Leetcode Solution
Companies:
LeetCode: Minimum Number Of Keypresses Leetcode Solution
Difficulty: Medium
Topics: greedy hash-table sorting string
Problem statement:
You are given a keyboard layout consisting of alphabets, and a string s that needs to be typed using this keyboard. Initially, your finger is at the position of letter 'A' of the keyboard. You need to find the minimum number of key presses required to type the given string s using this keyboard.
Constraints: 1 <= s.length <= 100 s consists of lowercase English letters.
Solution:
The problem requires us to find the shortest path from 'A' to each letter of the input string s, and then add up all these distances to get the minimum number of key presses required.
To calculate the shortest path from 'A' to each letter, we can use BFS. We will start the BFS from 'A' and keep a visited array to ensure that we don't revisit any letter. We will also keep a distance array to store the shortest distance from 'A' to each letter.
Next, we will iterate through the input string s and for each letter in s, we will add the shortest distance from 'A' to that letter in our result.
Let's implement the above solution:
int minKeyPresses(string s) { vector<vector<int>> graph(26); // Construct graph for keyboard layout for(int i=0; i<25; i++) { graph[i].push_back(i+1); graph[i+1].push_back(i); } unordered_map<char, int> keyMap; for(int i=0; i<26; i++) { keyMap['a'+i] = i; } // BFS to find shortest distance from A to each key vector<int> distance(26, INT_MAX); vector<bool> visited(26, false); distance[0] = 0; queue<int> q; q.push(0); visited[0] = true; while(!q.empty()) { int u = q.front(); q.pop(); for(int v : graph[u]) { if(!visited[v]) { distance[v] = distance[u]+1; visited[v] = true; q.push(v); } } } // Calculate minimum number of key presses int res = 0; int currentPos = 0; for(char ch : s) { int newPos = keyMap[ch]; res += abs(distance[currentPos]-distance[newPos]); currentPos = newPos; } return res; }
The time complexity of the solution is O(N), where N is the length of the input string s, since BFS takes O(N) time to traverse the graph and we iterate over the input string s of length N. The space complexity is also O(N), since we use arrays of size 26 to store the graph, distance and visited arrays.
Minimum Number Of Keypresses Solution Code
1