Simulated Stock Trading Signals and Two-Char String Reduction
Stacks & QueuesModel answerLast updated
Solve two streaming state problems: daily stock trading based on sign patterns in O(N) time and two-character substring elimination using an in-place stack.
This multi-part problem tests your ability to process streaming data and maintain efficient state updates under strict time and memory bounds.
Task 1: Stock Trading by Sign Pattern Matching
You are given an integer array prices of size $N$ representing daily stock prices. You are also given two arrays of non-zero integers: buy_pattern (length $K_b$) and sell_pattern (length $K_s$). Both patterns consist exclusively of 1 (indicating a price increase from the previous day) and -1 (indicating a price decrease).
- Define the direction of price change on day $t$ ($t \ge 1$) as: $$\text{sign}(prices[t] - prices[t-1]) = \begin{cases} 1 & \text{if } prices[t] > prices[t-1] \ -1 & \text{if } prices[t] < prices[t-1] \ 0 & \text{if } prices[t] == prices[t-1] \end{cases}$$
- A pattern of length $k$ matches at day $t$ if the last $k$ daily signs $[\text{sign}(prices[t-k+1] - prices[t-k]), \dots, \text{sign}(prices[t] - prices[t-1])]$ are identical to the pattern. Note: A sign of
0(flat price) breaks any potential match, as patterns contain only1and-1. - You start on day 0 with 0 shares. On each day $t \ge 1$:
- Check for a
sell_patternmatch. If matched and your current holdings are $> 0$, sell 1 share. - Check for a
buy_patternmatch. If matched, buy 1 share. - If both patterns match on the same day, process the sell operation first, followed by the buy operation.
- Short selling is forbidden; holdings can never drop below 0.
- Check for a
Return an integer array holdings of length $N$, where holdings[t] is the number of shares held at the end of day $t$.
Target Complexity: $O(N)$ time and $O(1)$ extra space (excluding the output array).
Task 2: Iterative Removal of Forbidden Two-Character Pairs
You are given a string s and a set forbidden_pairs containing disallowed two-character combinations of lowercase English letters (e.g., {"ab", "bc", "cd"}).
Repeatedly delete any occurrence of any two-character pair in forbidden_pairs from s until no such pairs remain.
- Write a function that returns the length of the resulting string.
- Explain how to return the final string itself.
- Discuss the space and time complexity, aiming for $O(N)$ time and $O(1)$ extra space beyond an in-place buffer (or $O(\min(N, \Sigma))$ auxiliary space, where $\Sigma$ is the alphabet size).
Constraints:
- $N \le 2 \times 10^5$
forbidden_pairscontains at most $26 \times 26 = 676$ unique pairs.
Hints
Hint 1
For Task 1: Re-evaluating the full pattern array of length K every day takes O(N * K) time. Can you maintain a rolling window of recent signs using a bitmask, along with a counter for consecutive non-zero diffs?
Hint 2
For Task 1: Remember to process sells before buys on the same day, and ensure holdings never go below zero.
Hint 3
For Task 2: Standard left-to-right greedy elimination can be implemented with a stack. How can you perform this stack operation in O(1) extra space if the input string is mutable?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Solution
Task 1: Stock Trading by Sign Pattern Matching
Approach & Algorithm
A naive check evaluates all $K$ elements of each pattern on every day $t$, resulting in $O(N \cdot \max(K_b, K_s))$ time. To achieve $O(N)$ overall runtime:
- Bitmask Rolling Window: Map
+1to bit1and-1to bit0. Keep a rolling integerwindowcontaining the encoded signs. - Consecutive Non-Zero Count: Track
consecutive_signs, the number of consecutive days with non-zero diffs (+1or-1). If $prices[t] - prices[t-1] == 0$, resetconsecutive_signs = 0and clearwindow. - O(1) Pattern Verification: Pre-encode
buy_patternandsell_patterninto bitmasksmask_buyandmask_sell. At day $t$, a pattern of length $k$ matches if and only ifconsecutive_signs >= kAND the low $k$ bits ofwindowmatch the precomputed pattern mask. - Ordering & Rules: Process sell operations before buy operations. Ensure
holdingsnever drops below0.
Python Code
def calculate_holdings(prices, buy_pattern, sell_pattern):
n = len(prices)
if n == 0:
return []
holdings = [0] * n
def encode_pattern(pat):
val = 0
for x in pat:
val = (val << 1) | (1 if x == 1 else 0)
return val
kb, ks = len(buy_pattern), len(sell_pattern)
mask_b = encode_pattern(buy_pattern)
mask_s = encode_pattern(sell_pattern)
bit_mask_b = (1 << kb) - 1 if kb > 0 else 0
bit_mask_s = (1 << ks) - 1 if ks > 0 else 0
max_k = max(kb, ks, 1)
full_mask = (1 << max_k) - 1
window = 0
consecutive_signs = 0
current_held = 0
for t in range(1, n):
diff = prices[t] - prices[t - 1]
if diff == 0:
consecutive_signs = 0
window = 0
else:
consecutive_signs += 1
sign_bit = 1 if diff > 0 else 0
window = ((window << 1) | sign_bit) & full_mask
# Process SELL first
if ks > 0 and consecutive_signs >= ks:
if (window & bit_mask_s) == mask_s and current_held > 0:
current_held -= 1
# Process BUY second
if kb > 0 and consecutive_signs >= kb:
if (window & bit_mask_b) == mask_b:
current_held += 1
holdings[t] = current_held
return holdings
Complexity Analysis
- Time Complexity: $O(N)$. Bitwise updates and comparisons run in $O(1)$ time per day assuming standard integer word sizes ($K \le 64$). If patterns are arbitrarily long ($K > 64$), KMP automata over the sign stream achieve strict $O(N + K_b + K_s)$ time.
- Space Complexity: $O(1)$ auxiliary space beyond the output array.
Task 2: Iterative Removal of Forbidden Substrings
Approach & Algorithm
To perform left-to-right iterative removal (leftmost-first deletion):
- Stack Reduction: Use a stack to hold valid prefix characters. Iterate through the string character by character.
- In-Place Processing: Simulate the stack using a write pointer
write_idxdirectly over a character array. Sincewrite_idx <= read_idxalways holds, no unread data is overwritten. - Fast Lookup: Represent
forbidden_pairsas a fixed $26 \times 26$ boolean table (or a hash set) to achieve $O(1)$ pair validation.
When processing character c:
- If
write_idx > 0and the pair(buffer[write_idx - 1], c)is inforbidden_pairs, pop from the stack by decrementingwrite_idx -= 1. - Otherwise, push
cby settingbuffer[write_idx] = cand incrementingwrite_idx += 1.
Python Code
def remove_forbidden_pairs(s: str, forbidden_pairs: set) -> tuple[int, str]:
"""
Returns (final_length, reduced_string) after left-to-right pair removals.
"""
# Fast O(1) lookup table using pair tuples or string matches
# Convert string to list for mutable in-place array simulation
buf = list(s)
write_idx = 0
for ch in s:
if write_idx > 0 and (buf[write_idx - 1] + ch) in forbidden_pairs:
write_idx -= 1 # Pop top of stack
else:
buf[write_idx] = ch
write_idx += 1 # Push onto stack
final_str = "".join(buf[:write_idx])
return write_idx, final_str
Leftmost Reduction vs. Optimal Reduction Subtlety
An important discussion point during an interview is confluence (order independence):
- Left-to-right greedy elimination reduces
saccording to the leftmost available match. - For arbitrary pair sets, different choices of overlapping removals may yield different final lengths. For example, if
forbidden_pairs = {"ab", "bc", "cd"}ands = "abcd":- Removing
"bc"first leaves"ad"(length 2). - Removing
"ab"then"cd"leaves""(length 0).
- Removing
- If the objective were to find the global minimum possible length under arbitrary reduction orders, the problem reduces to context-free grammar parsing (Interval DP) running in $O(N^3)$ time. However, standard online assessments and streaming models specify leftmost-greedy reduction, which runs in $O(N)$ time via stack-based evaluation.
Complexity Analysis
- Time Complexity: $O(N)$. Each character is pushed onto and popped from the stack at most once. Pair checks take $O(1)$ time.
- Space Complexity: $O(1)$ auxiliary space in languages with mutable strings (e.g., C++
std::stringmodified in-place) or $O(\Sigma^2)$ to store the pair lookup table. In Python, initializinglist(s)takes $O(N)$ space due to string immutability.