FastPrepDecode Ways

Decode Ways

Bloomberg LP logoBloomberg LP● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

The mapping 1 -> A, 2 -> B, ..., 26 -> Z encodes letters as decimal numbers.

Given a nonempty digit string digits, return the number of distinct ways to decode the entire string. A code cannot have a leading zero, so 06 is invalid while 6 is valid.

Function

numDecodings(digits: String) → int

Examples

Example 1

digits = "12"return = 2

The two decodings are AB using 1,2 and L using 12.

Example 2

digits = "226"return = 3

The valid decodings correspond to 2,2,6, 22,6, and 2,26.

Example 3

digits = "06"return = 0

A code cannot begin with 0, so the entire string has no valid decoding.

Constraints

  • 1 <= digits.length <= 100
  • digits contains only characters 0 through 9.
  • The answer fits in a signed 32-bit integer.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int numDecodings(String digits) {
    // Write your code here.
}
digits"12"
expected2
Checking account…