15(June) Mobile numeric keypad
15. Mobile Numeric Keypad
The problem can be found at the following link: Question Link
Problem Description
There is a standard numeric keypad on a mobile phone. You can only press the current button or buttons that are directly up, left, right, or down from it. Diagonal movements and pressing the bottom row corner buttons (* and #) are prohibited.
Given a number n, find the number of possible unique sequences of length n that you can create by pressing buttons. You can start from any digit.
Example:
Input:
Output:
Explanation: Number of possible numbers are 10 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
My Approach
Initialization:
Define a 2D vector
arepresenting the keypad, where-1represents invalid keys (* and #).Create a 3D array
dpwheredp[i][j][k]stores the number of unique sequences of lengthkstarting at key(i, j)on the keypad.
Base Case:
Initialize
dp[i][j][1]to 1 for all valid keys(i, j)since any key by itself is a valid sequence of length 1.
Dynamic Programming Transition:
For each length from 2 to
n, and for each key(i, j):Update
dp[i][j][len]by adding the number of sequences of lengthlen-1from the current key and its valid neighbors (up, down, left, right).
Result Calculation:
Sum up the values in
dp[i][j][n]for all valid keys(i, j)to get the total number of unique sequences of lengthn.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we iterate through the length of sequences up to
nand update thedparray.Expected Auxiliary Space Complexity: O(n), as the
dparray stores values up to lengthn.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated