Show problems as
Classic problem #3614HardStringSimulation

Process String with Special Operations II

Real-world version: Character at a Slot of the Built Tape
Tracked in this browser only
Read Process String with Special Operations II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A tape starts empty. The string s is read left to right, one character at a time, and each character is an instruction:

  • a lowercase letter appends that letter to the end of the tape;
  • '*' removes the last character of the tape, and does nothing when the tape is already empty;
  • '#' appends a copy of the whole tape to itself, so the tape doubles in length;
  • '%' reverses the tape.

Return the character sitting at slot k of the finished tape, counting slots from 0. If the finished tape holds k characters or fewer, return "." instead.

Examples

Example 1

Input
s = "ab#", k = 3
Output
"b"

The tape reads "ab" after two letters, then doubling makes it "abab". Slot 3 of that tape holds "b".

Example 2

Input
s = "ab%", k = 0
Output
"b"

Reversing "ab" gives "ba", so slot 0 holds "b".

Example 3

Input
s = "a", k = 1
Output
"."

The finished tape holds one character, so slot 1 is past its end and the answer is ".".

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters and the characters '*', '#' and '%' only
  • 0 <= k <= 1000000000000000
  • The finished tape never holds more than 10^15 characters

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def char_at_position(s: str, k: int) -> str:
Java
public char charAtPosition(String s, long k)