AlgoMaster Logo

Decode Ways

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

The recursive approach attempts to solve the problem by considering each character individually and tries to decode either one or two characters at a time. This explores all possible combinations leading to a solution.

Intuition:

  • If we encounter a single character from '1' to '9', it can be decoded to a letter from 'A' to 'I'.
  • A pair of characters from '10' to '26' can be decoded into a letter from 'J' to 'Z'.
  • We return 0 if the current character is '0' because it doesn't map to any letter directly.
  • For each character, recursively calculate the number of ways to decode the subsequent string.

Code:

2. Memoization Approach

The memoization approach is an optimization over the recursive approach where we store the results of subproblems to avoid redundant calculations.

Intuition:

  • We use an array to store results of previously computed indices, avoiding recalculations and reducing time complexity.
  • Similar recursive structure, but check the memoized results before computing.

Code:

3. Dynamic Programming Approach

The DP approach builds from the bottom up, filling an array where each position represents the number of ways to decode up to that point.

Intuition:

  • Use a dp array where dp[i] stores the count of decode ways up to index i.
  • Initialize dp[0] to 1 as the base case (empty string).
  • Iterate through the string, filling dp based on allowable single and double character decodings.

Code: