Coding questions · Oracle
Compute letter frequencies from encoded string
This question evaluates proficiency in string parsing and frequency aggregation, specifically handling mixed-length encodings, tokenization of digits and '#' markers, and parsing numeric repetition counts while respecting linear-time and constant-space constraints.
Problem
You are given an encoded string s representing a string of lowercase English letters (a–z). The encoding follows these rules:
- Letters
atoiare encoded as digits1to9.a -> "1",b -> "2", …,i -> "9"
- Letters
jtozare encoded as two digits followed by#.j -> "10#",k -> "11#", …,z -> "26#"
- If a letter repeats consecutively
k >= 2times, the repetition is encoded by appending"(k)"immediately after that letter’s code.- Example:
"aa" -> "1(2)","ccc" -> "3(3)","jj" -> "10#(2)"
- Example:
Task
Return an integer array counts of length 26, where counts[0] is the number of 'a' characters in the decoded string, counts[1] is the number of 'b', …, and counts[25] is the number of 'z'.
Examples
s = "1226#24#"decodes to"abzx".s = "1(2)23(3)"decodes to"aabccc".s = "2110#(2)"decodes to"bajj".s = "23#(2)24#25#26#23#(3)"decodes to"wwxyzwww".
Input/Output
- Input: a string
sconsisting of digits,#,(, and)that follows the encoding rules above. - Output: an array of 26 integers with letter frequencies.
Notes / Constraints (reasonable interview assumptions)
sis validly encoded.- Counts in parentheses can be multiple digits (e.g.,
(12)). - Aim for
O(|s|)time andO(1)extra space (excluding the output array).
Compute letter frequencies from encoded string
Hints
- Scan left to right. The only way to tell a two-digit letter (10#..26#) from a single digit is to peek two characters ahead for a '#'.
- After consuming a letter's code, check whether the next character is '('. If so, read the integer up to ')' — it can be more than one digit — and use it as the multiplier; otherwise the letter occurs once.
- Map the numeric value v (1..26) to array index v-1 and add the repetition count there.