Decode Ways - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Approach (Dynamic Programming with Two Running Counts)

We compute the number of decodings of the input string s using a constant-space DP that scans left-to-right. At each step, we consider whether the current character can form a valid single-digit code (1–9) and whether the previous+current characters can form a valid two-digit code (10–26).

  • State (running variables):
    • lastWays — number of ways to decode up to the last evaluated character.
    • prevWays — number of ways to decode up to the character before the last evaluated one.
  • Initialization / Base cases:
    • If s[0] = '0', there are no valid decodings → return 0.
    • Otherwise, set prevWays = 1 (empty prefix has one way) and lastWays = 1 (a non-zero first digit has exactly one decoding).
  • Transition (for each index i from 1 to s.length-1):
    • Start newWays = 0.
    • Single-digit check: If s[i] ∈ {'1'..'9'}, add lastWays to newWays (any decoding up to the last evaluated character can be extended by this valid digit).
    • Two-digit check: If s[i-1]s[i] ∈ {"10".."26"}, add prevWays to newWays (any decoding up to the character before the last evaluated one can be extended by this valid pair).
    • Shift the window forward: prevWays = lastWays, lastWays = newWays.
  • Processing order: Left-to-right, updating only the two running counts. No DP array is stored.
  • Result: After the scan, lastWays is the total number of decodings of the whole string.

Edge Conditions

  • Leading zero (s[0] = '0') is invalid → immediately return 0.
  • Single zeros never decode alone; they only participate in valid pairs "10" or "20".

Time Complexity

Each character in the input string is processed once, and for each position, we perform a constant amount of work. Therefore, the overall time complexity is O(n), where n is the length of the string.

Space Complexity

Since we only keep track of just a few variables, the space complexity is O(1).

Visucodize editorial solution titled JS Solution for LeetCode's Decode Ways coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/decode-ways.