Leetcode 91: Decode Ways

grid47
grid47
Exploring patterns and algorithms
Oct 28, 2024 6 min read

A glowing key unlocking multiple pathways, symbolizing decoding and transformation.
Solution to LeetCode 91: Decode Ways Problem

You have intercepted a string of numbers that encodes a message. The message is decoded using the following mapping:

“1” -> ‘A’, “2” -> ‘B’, … “26” -> ‘Z’.

However, there are multiple ways to decode the string, as some numbers can represent a single letter (e.g., ‘1’ for ‘A’, ‘12’ for ‘L’). Your task is to return the number of possible ways to decode the string. Note that strings containing invalid encodings (e.g., starting with zero or having codes larger than 26) should not be considered valid.

Problem
Approach
Steps
Complexity
Input: The input is a string s consisting only of digits, representing the encoded message.
Example: Input: s = "1234"
Constraints:
• 1 <= s.length <= 100
• s contains only digits
Output: The output is an integer, representing the number of valid ways to decode the string.
Example: Output: 3
Constraints:
• The output should fit within a 32-bit integer.
Goal: The goal is to count the number of ways the string can be decoded, by considering all possible valid groupings of numbers into letters and ensuring no invalid decodings (such as those starting with 0).
Steps:
• Check if the first character is '0', which would make the string invalid.
• Use dynamic programming or memoization to store the number of ways to decode the string from each position.
• At each step, consider both single-digit and two-digit numbers (if valid), and recursively calculate the number of decodings for the remaining substring.
Goal: The input string must only contain digits. Strings that start with '0' or have invalid groupings (e.g., '30') should return 0.
Steps:
• The string should contain only digits.
• The number of decodings should not exceed the maximum value of a 32-bit integer.
Assumptions:
• The input string is guaranteed to be non-empty and contain only digits.
Input: Input: s = "1234"
Explanation: "1234" can be decoded in three ways: as 'ABCD' (1 2 3 4), 'LCD' (12 3 4), or 'AWD' (1 23 4).

Input: Input: s = "226"
Explanation: "226" can be decoded as: 'BBF' (2 2 6), 'VF' (22 6), or 'BZ' (2 26).

Input: Input: s = "06"
Explanation: "06" cannot be decoded because '06' is not a valid encoding, so the output is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus