27. Mobile Numeric Keypad
โ GFG solution to the Mobile Numeric Keypad problem: count unique sequences of length n using keypad movements with dynamic programming. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
You have a standard numeric keypad on a mobile phone. You can press the current button or any button that is directly above, below, left, or right of it. Diagonal movements and pressing the bottom row corner buttons (* and #) are not allowed.
Given an integer n, determine how many unique sequences of length n can be formed by pressing buttons on the keypad, starting from any digit.
Keypad Layout:
๐ Examples
Example 1
Input: n = 1
Output: 10
Explanation: Possible 1-digit numbers follow keypad moves -
From 0 โ 0, 1 โ 1, 2 โ 2 and so on, total 10 valid combinations are possible.Example 2
Input: n = 2
Output: 36
Explanation: Possible 2-digit numbers follow keypad moves -
From 0 โ 00, 08 (2),
From 1 โ 11, 12, 14 (3),
From 3 โ 33, 32, 36 (3), and so on,
total 36 valid combinations are possible.๐ Constraints
$1 \le n \le 15$
โ
My Approach
The optimal approach uses Dynamic Programming with a 2D array representing the keypad layout. We simulate the keypad as a 4ร3 grid and use direction vectors to handle valid movements.
Dynamic Programming with 2D Grid Simulation
Model the Keypad:
Represent keypad as a 4ร3 grid where [3][0] and [3][2] are invalid (* and # positions).
Initialize all valid positions with 1 (base case for n=1).
Define Movement Directions:
Use direction vectors: stay in place (0,0), up/down/left/right movements.
This allows pressing current button or adjacent buttons.
Iterative DP Transition:
For each step from 2 to n, calculate new possibilities.
For each position, sum up contributions from all reachable positions.
Use two arrays (previous and current) to avoid overwriting.
Boundary Handling:
Skip invalid keypad positions ([3][0] and [3][2]).
Ensure movements stay within 4ร3 grid bounds.
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the sequence length. We iterate n-1 times, and for each iteration, we process a constant 4ร3 grid with constant direction moves.
Expected Auxiliary Space Complexity: O(1), as we only use two fixed-size 4ร3 arrays regardless of input size, making it constant extra space.
๐งโ๐ป 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