Map numbers to characters in JavaScript

When mapping numbers to characters in JavaScript, we need to convert digits to their corresponding alphabetical positions (1='a', 2='b', etc.). A number can be mapped in multiple ways by grouping digits differently.

For example, the number 12145 can be interpreted as:

  • 1,2,1,4,5 ? a,b,a,d,e
  • 12,1,4,5 ? l,a,d,e
  • 12,14,5 ? l,n,e

However, combinations like 1,2,1,45 are invalid because 45 exceeds the alphabet range (1-26).

Solution Approach

We use recursion to explore all valid digit groupings. For each position, we can take either one digit (1-9) or two digits (10-26) if both are valid.

Example

const num = 12145;

const mapToAlphabets = num => {
    const numStr = '' + num;
    let res = [];
    
    const shoveElements = (left, right) => {
        if (!left.length) {
            res.push(right.map(el => {
                return (+el + 9).toString(36);
            }).join(''));
            return;
        };
        
        if (+left[0] > 0) {
            shoveElements(left.slice(1), right.concat(left[0]));
        };
        
        if (left.length >= 2 && +(left.slice(0, 2)) 

[ 'abade', 'abne', 'aude', 'lade', 'lne' ]

How It Works

The algorithm uses a recursive helper function shoveElements that:

  • Takes one digit if it's valid (1-9)
  • Takes two digits if the combination is valid (10-26)
  • Converts numbers to letters using (+el + 9).toString(36)
  • Base case: when no digits remain, add the current mapping to results

Key Points

  • Single digits must be 1-9 (not 0)
  • Two-digit combinations must be 10-26
  • The conversion formula (+el + 9).toString(36) maps 1?'a', 2?'b', etc.
  • All valid permutations are explored through backtracking

Conclusion

This solution efficiently finds all valid alphabet mappings for a given number using recursive backtracking. The key is validating digit ranges and exploring both single and double-digit possibilities.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements