Skip to main content

Process String with Special Operations II - Solution & Explanation

HardStringSimulation10 min readAsked at: Amazon, Meta, Google
Practice this problem

Problem Statement

You are given a string s consisting of lowercase English letters and the special characters: '*', '#', and '%'.

You are also given an integer k.

Build a new string result by processing s according to the following rules from left to right:

  • If the letter is a lowercase English letter append it to result.
  • A '*' removes the last character from result, if it exists.
  • A '#' duplicates the current result and appends it to itself.
  • A '%' reverses the current result.

Return the kth character of the final string result. If k is out of the bounds of result, return '.'.

 

Example 1:

Input: s = "a#b%*", k = 1

Output: "a"

Explanation:

i s[i] Operation Current result
0 'a' Append 'a' "a"
1 '#' Duplicate result "aa"
2 'b' Append 'b' "aab"
3 '%' Reverse result "baa"
4 '*' Remove the last character "ba"

The final result is "ba". The character at index k = 1 is 'a'.

Example 2:

Input: s = "cd%#*#", k = 3

Output: "d"

Explanation:

i s[i] Operation Current result
0 'c' Append 'c' "c"
1 'd' Append 'd' "cd"
2 '%' Reverse result "dc"
3 '#' Duplicate result "dcdc"
4 '*' Remove the last character "dcd"
5 '#' Duplicate result "dcddcd"

The final result is "dcddcd". The character at index k = 3 is 'd'.

Example 3:

Input: s = "z*#", k = 0

Output: "."

Explanation:

i s[i] Operation Current result
0 'z' Append 'z' "z"
1 '*' Remove the last character ""
2 '#' Duplicate the string ""

The final result is "". Since index k = 0 is out of bounds, the output is '.'.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters and special characters '*', '#', and '%'.
  • 0 <= k <= 1015
  • The length of result after processing s will not exceed 1015.

Approach Overview

Problem Overview: You receive a string and a set of special operations that modify the current sequence while scanning it. Some operations append characters, others remove or transform previously processed parts. The goal is to simulate these rules and return the final string after all operations are applied.

Approach 1: Direct Simulation with Mutable String (O(n^2) time, O(n) space)

The most straightforward way is to simulate every operation exactly as described. Iterate through the input string and maintain a mutable result string. When a special symbol appears, apply its effect immediately: append characters, remove the last character, or rebuild the string depending on the rule. This approach is simple but inefficient because operations like reversing or repeated concatenation can repeatedly copy the string, leading to O(n^2) time in the worst case. It works for small inputs but will likely time out for large constraints.

Approach 2: Stack / Deque Based Simulation (O(n) time, O(n) space)

A more efficient method treats the result as a dynamic structure such as a stack or deque. Iterate through the characters and push normal characters into the structure. When an operation appears, update the structure instead of rebuilding the entire string. For example, a delete-style operation simply performs a stack pop, while insertions become push operations. If the operation changes ordering (like reversing behavior), track the direction using a flag and push to the front or back accordingly. Each character is processed at most once, which keeps the complexity at O(n). This pattern is a classic combination of string processing and simulation.

Approach 3: Lazy Operation Tracking (O(n) time, O(n) space)

When operations repeatedly affect the entire string (such as toggling direction or applying batch transformations), rebuilding after every step is expensive. Instead, record the operation state lazily. Maintain flags or counters representing the current transformation state, and only apply them when inserting or extracting characters. A deque works well here because you can append on both ends while respecting the current direction. This reduces repeated work and keeps each step constant time. The approach often appears in advanced stack and simulation problems where operations interact with previously processed characters.

Recommended for interviews: Interviewers expect the linear-time simulation using a stack or deque. The brute-force approach demonstrates you understand the rules of the operations, but the optimized simulation shows you can control time complexity and avoid repeated string rebuilding. Mention that each character is processed once and that all operations translate to constant-time stack or deque updates.

Solution

We first calculate the length m of the processed result string result. If k geq m, it indicates that k exceeds the valid indices of the result string, so we return '.'.

Otherwise, we traverse the string s in reverse order and handle each character based on the following cases:

  1. If s[i] is '*', we increase m by 1.
  2. If s[i] is '#', we divide m by 2. At this point, if k geq m, we subtract m from k.
  3. If s[i] is '%', we update k to m - 1 - k.
  4. Otherwise, s[i] is a letter. We decrease m by 1. If k = m, it means we have found the k-th character, so we return s[i].

The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Direct String SimulationO(n^2)O(n)Good for understanding the rules or very small inputs
Stack / Deque SimulationO(n)O(n)General case where operations modify recent characters
Lazy Operation TrackingO(n)O(n)Best when operations frequently affect string direction or global state

Video Solution

Process String with Special Operations II | Simplified | Dry Runs | Leetcode 3614 | codestorywithMIK • codestorywithMIK • 15,751 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Process String with Special Operations II easy or hard?
Process String with Special Operations II is categorized as Hard because multiple operations interact with previously processed characters. The challenge comes from designing an efficient simulation that avoids repeatedly rebuilding the string and keeps the runtime linear.
Process String with Special Operations II Python/Java solution
The implementation typically iterates through the string and maintains a stack or deque. Python solutions often use collections.deque for efficient front and back operations, while Java solutions use ArrayDeque. C++ implementations commonly rely on deque or vector depending on the operation rules.
How to solve Process String with Special Operations II in O(n)?
Scan the string once and maintain a stack or deque to store the current result. When encountering a normal character, append it to the structure. When encountering a special operation, apply the corresponding action such as removing the last element, toggling direction, or inserting at the front. Avoid rebuilding the entire string during processing.
What is the best approach for Process String with Special Operations II?
The most efficient approach uses stack or deque based simulation. Iterate through the string and treat each special symbol as an operation that modifies the data structure. Characters are pushed or removed in constant time, and direction-changing operations can be handled with a flag. This results in O(n) time and O(n) space.
Is Process String with Special Operations II asked at Google/Amazon/Meta?
String simulation problems with stack or deque manipulation frequently appear in interviews at companies like Amazon, Google, and Meta. Variants often include processing backspace characters, reversing segments, or applying command-style operations to strings.
What data structure is used in Process String with Special Operations II?
A stack or deque is the most common data structure for this problem. Stacks are useful when operations affect recently added characters, while deques help when characters may need to be added or removed from both ends depending on the current operation state.
What is the time complexity of Process String with Special Operations II?
The optimal solution runs in O(n) time because each character from the input string is processed once. Stack or deque operations such as push, pop, and append are constant time. Space complexity is O(n) to store the resulting characters.

Ready to solve this problem?

Practice Process String with Special Operations II with our built-in code editor and test cases.

Practice on FleetCode