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.

Image

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

  1. Initialization:

    • Define a 2D vector a representing the keypad, where -1 represents invalid keys (* and #).

    • Create a 3D array dp where dp[i][j][k] stores the number of unique sequences of length k starting at key (i, j) on the keypad.

  2. 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.

  3. 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 length len-1 from the current key and its valid neighbors (up, down, left, right).

  4. 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 length n.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), as we iterate through the length of sequences up to n and update the dp array.

  • Expected Auxiliary Space Complexity: O(n), as the dp array stores values up to length n.

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