InterviewDB Question

Digit Encoder: Encode an Integer Using a Custom Digit Alphabet and Base

Question Details

Problem

Implement an encoder that converts non-negative integers to and from a custom alphabet of n symbols, effectively treating the alphabet as a base-n number system. The first symbol represents 0.

python
def encode(n: int, alphabet: str) -> str:
    # encode integer n using alphabet as base-len(alphabet) digits
    pass

def decode(s: str, alphabet: str) -> int:
    pass

Example:

alphabet = "0123456789ABCDEF"  # hex
encode(255, alphabet)  -> "FF"
decode("FF", alphabet) -> 255

alphabet = "ABCDEFGHIJKLMNOP"  # custom base-16
encode(255, alphabet)  -> "PP"
decode("PP", alphabet) -> 255

alphabet = "01"  # binary
encode(10, alphabet)   -> "1010"

Follow-ups

  1. What happens when n = 0? How do you handle the edge case to return the zero symbol rather than an empty string?
  2. How does this relate to Base62 encoding used in URL shorteners (alphabet = 0-9 + a-z + A-Z)?
  3. How would you add padding to ensure the output is always a fixed number of digits?
  4. What is the maximum integer representable by a 6-character string with a 62-symbol alphabet?

Full Details

Problem

Implement an encoder that converts non-negative integers to and from a custom alphabet of n symbols, effectively treating the alphabet as a base-n number system. The first symbol represents 0.

python
def encode(n: int, alphabet: str) -> str:
    # encode integer n using alphabet as base-len(alphabet) digits
    pass

def decode(s: str, alphabet: str) -> int:
    pass

Example:

alphabet = "0123456789ABCDEF"  # hex
encode(255, alphabet)  -> "FF"
decode("FF", alphabet) -> 255

alphabet = "ABCDEFGHIJKLMNOP"  # custom base-16
encode(255, alphabet)  -> "PP"
decode("PP", alphabet) -> 255

alphabet = "01"  # binary
encode(10, alphabet)   -> "1010"

Follow-ups

  1. What happens when n = 0? How do you handle the edge case to return the zero symbol rather than an empty string?
  2. How does this relate to Base62 encoding used in URL shorteners (alphabet = 0-9 + a-z + A-Z)?
  3. How would you add padding to ensure the output is always a fixed number of digits?
  4. What is the maximum integer representable by a 6-character string with a 62-symbol alphabet?

About This Question

This is a reported interview question from a anduril interview during the phone round.

It covers the following topics: Coding, Phone, Strings .