Letter at Position K of the Tape

MediumArrays & Hashing

Problem

A ticker tape is built from a code string read left to right, starting with an empty tape: a lowercase letter is appended to the tape, and a digit d (2–9) makes the tape consist of its current content written d times in a row.

For example "ab2c3" builds ab → abab → ababc → ababcababcababc. Return the k-th letter (1-indexed) of the final tape as a one-character string. The tape can be far too long to build.

Example 1

Input:
code = "ab2c3", k = 5
Output:
"c"

The tape is ababcababcababc; its 5th letter is c.

Example 2

Input:
code = "ab2c3", k = 7
Output:
"b"

Example 3

Input:
code = "x9", k = 4
Output:
"x"

Constraints

  • 2 ≤ code.length ≤ 100
  • code starts with a letter and contains only lowercase letters and digits 2–9.
  • 1 ≤ k ≤ final tape length ≤ 10^15

Hint

Show the first hint

First compute only the length of the tape after each character; you never need the content.

Walkthrough

How to approach it

01Clarify before coding

  • How long can the tape be? Up to 10^15 letters, so it cannot be built.
  • Is k 1-indexed? Yes.
  • Can the code start with a digit? No, it starts with a letter, so the tape is never empty when a digit is read.

02Brute force

Build the tape as a string following the rules and index into it.

Cost: O(final length) time and memory, up to 10^15: impossible.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.