Skip to main content
mediumBlind 75

Decode Ways

A message containing letters A-Z is encoded to numbers 1-26 Given a string of digits, return the number of ways to decode it Example: "12" => 2 ("AB" as 1,2 or "L" as 12) Example: "226" => 3 ("BZ" as 2,26 or "VF" as 22,6 or "BBF" as 2,2,6) Note: "06" is invalid (no mapping), so it returns 0

A message of uppercase letters is encoded by mapping 'A' to 1, 'B' to 2, and so on up to 'Z' to 26. Given a non-empty string s of digits, return the number of ways to split it back into letters. Every chunk must be a number from 1 to 26 written without a leading zero, so '06' cannot be decoded and returns 0. For example, '12' decodes 2 ways and '226' decodes 3 ways.

Examples

You write

num_decodings(s: str)

  1. Example 1

    Input
    s = "12"
    returns
    2
  2. Example 2

    Input
    s = "226"
    returns
    3

The pattern behind it

Strings

I reach for it when

  • The input is text and the answer is a count, a substring or a new string.
  • You need to compare, reverse or rebuild characters.

Say this before you type. Say which array pattern the string is hiding before you touch a character.

All 51 Strings problems

Dynamic Programming

I reach for it when

  • Brute force repeats the same subproblem.
  • You are asked for a count, a minimum or a maximum.

Say this before you type. Say the state in one sentence, then say which smaller states it reads from.

All 37 Dynamic Programming problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Count Decode Waysmedium

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.