#3614

Process String with Special Operations II

Hard
StringSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of building the final string, we track the effective length and operations to determine the k-th character directly. This avoids unnecessary memory usage and time-consuming operations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Traverse the string in reverse, maintaining a list of effective lengths after each operation.
  2. 2Step 2: For each operation, adjust the index k based on the operation type (undo duplication or reversal).
  3. 3Step 3: After processing, return the character at the adjusted k-th index or '.' if out of bounds.
solution.py20 lines
1def process_string(s, k):
2    lengths = [0]
3    for char in s:
4        if char.islower():
5            lengths.append(lengths[-1] + 1)
6        elif char == '*':
7            lengths.append(lengths[-1] - 1)
8        elif char == '#':
9            lengths.append(lengths[-1] * 2)
10        elif char == '%':
11            lengths.append(lengths[-1])
12    if k >= lengths[-1]: return '.'
13    for i in range(len(s) - 1, -1, -1):
14        if lengths[i] == k:
15            return s[i]
16        if s[i] == '#':
17            k %= lengths[i]
18        elif s[i] == '%':
19            k = lengths[i] - 1 - k
20    return '.'

Complexity note: The optimal solution processes the string in linear time, maintaining a list of lengths, which allows us to efficiently determine the k-th character without building the entire result.

  • 1Operations can drastically change the string length.
  • 2Tracking lengths allows us to avoid full string construction.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.