Given a string S of size N, consisting of digits [0 – 9] and character ‘.’, the task is to print the string that can be obtained by pressing the mobile keypad in the given sequence.
Note: ‘.’ represents a break while typing.
Below is the image to represent the characters associated with each number in the keypad.
Input: S = “234”
Pressing the keys 2, 3, and 4 once gives the resultant string as “ADG”.
Input: S = “22.22”
Pressing the key 2 twice gives B, and then again pressing the key twice gives B. Therefore, the resultant string is “BB”.
Approach: The given problem can be solved by storing the mobile keypad mappings in an array and then traverse the string S and convert it into its equivalent string. Follow the steps below to solve the problem:
- Initialize an empty string, say ans to store the required result.
- Store the string associated to each key in the mobile keypad in an array nums such that nums[i] represent the set of characters on pressing the digit i.
- Traverse the given string S using the variable i and perform the following steps:
- If S[i] is equal to ‘.’, then increment i by 1, and continue to the next iteration.
- Otherwise, initialize a variable cnt as 0 to store the count of the same characters.
- Iterate until S[i] is equal to S[i + 1] and in each iteration check the following conditions:
- If cnt is equal to 2 and S[i] is 2, 3, 4, 5, 6, or 8, then break out of the loop because keys: 2, 3, 4, 5, 6, and 8 contain the same number of characters, i.e., 3.
- If cnt is equal to 3 and S[i] is 7 or 9, then break out of the loop because keys: 7 and 9 contain the same number of characters, i.e., 4.
- Increment the value of cnt and i by 1.
- If S[i] is either 7 or 9, then add the character nums[str[i]][cnt%4] to the string ans.
- Otherwise, add the character nums[str[i]][cnt%3] to the string ans.
- Increment the value of i by 1.
- After completing the above steps, print the value string ans as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live