Live String Index Store with Closest-Match Queries
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests ability to design a data structure that supports streaming character appends, point updates, and O(log N) nearest-occurrence queries over a mutable string.
Problem
You are building a live text buffer that grows and changes over time. The buffer starts with an initial string and must support three operations efficiently:
- Extend — push a single lowercase letter onto the end of the buffer.
- Overwrite — replace the letter at a given position with a new one.
- Closest occurrence — given a position and a target letter, find the smallest distance between that position and any occurrence of that letter anywhere in the buffer.
Implement the function live_char_store(s, operations, arguments) that processes a sequence of such operations against an initial string and returns the results.
Operations
| Operation | Arguments | Returns |
|---|---|---|
"append" | [ch] | None |
"update" | [index, ch] | None |
"closest" | [index, target] | int |
"append": addchto the right end of the buffer. The new character is immediately visible to subsequent queries."update": set the character at positionindextoch. Ifchalready equals the current character at that position, the buffer is unchanged."closest": return the minimum value of|index - j|over all positionsjwhere the buffer currently holdstarget. Return-1iftargetis not present anywhere in the buffer.
Constraints
1 <= len(s) <= 10^5chandtargetare lowercase English letters ('a'–'z').0 <= index < current_buffer_lengthfor every"update"and"closest"call.- At most
10^5total operation calls across all three types combined. - The initial string contains only lowercase English letters.
Notes
- The target letter may sit exactly at
index, in which case the answer is0. - When two occurrences of the target are equidistant from
index(one to the left, one to the right), return that shared distance. - An
"update"where the new character equals the existing one counts as a no-op and returnsNonewithout changing any internal state.
Examples
Example 1
Input: live_char_store('aabac', ['find_nearest', 'find_nearest', 'find_nearest', 'append', 'find_nearest', 'update', 'find_nearest'], [[2, 'a'], [2, 'c'], [0, 'z'], ['z'], [0, 'z'], [1, 'z'], [0, 'z']])
Output: [1, 2, -1, None, 5, None, 1]
Hints
Hint 1
For each of the 26 letters, track the set of positions where that letter currently appears. A query only ever needs to look at one of those 26 sets.
Hint 2
The closest occurrence is always either the largest stored position that is ≤ index (the predecessor) or the smallest stored position that is > index (the successor). You only need those two candidates.
Hint 3
Python has no built-in balanced BST, but you can implement a treap using flat arrays indexed by string position. Use a deterministic hash of the position as the heap priority so that sequentially appended indices still produce a balanced tree.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why the naive scan is too slow
A straightforward query scans outward from index until it finds target. In the worst case that is O(N) per query. With up to 10^5 operations on a buffer that can reach 2·10^5 characters, that costs around 10^10 steps — too slow for a 1-second time limit.
Core observation: 26 independent ordered sets
Only two candidates can ever be the closest occurrence of target:
- The predecessor — the rightmost position
j ≤ indexwherebuf[j] == target. - The successor — the leftmost position
j > indexwherebuf[j] == target.
Every other occurrence is farther away than whichever of those two is closer. So the query reduces to a predecessor/successor lookup in an ordered set of positions.
Maintain 26 such sets, one per letter. A query for target only touches that letter's set. Inserts and deletes are triggered by append and update.
Data structure: treap backed by flat arrays
Python has no built-in balanced BST. A treap gives O(log N) expected insert, delete, and predecessor/successor. The implementation here uses a compact flat-array representation:
- Node id = buffer position. Each position belongs to exactly one letter's treap at any moment, so a single global
left,right, andpriorityarray is enough for all 26 trees.roots[c]holds the root node of letterc's treap. - Deterministic priorities are computed as
((index + 1) × 2654435761) mod 2^32(Knuth multiplicative hashing). This scrambles the sequential indices thatappendproduces, keeping the tree balanced in expectation without a random-number generator. split(root, key)partitions the tree into nodes with id< keyand nodes with id≥ key.merge(a, b)joins two trees when every id inais less than every id inb.insertanderaseare built fromsplitandmergein the standard way.
Predecessor/successor in one pass
The query descends from the root of target's treap:
- If
current ≤ index, recordcurrentas the new best predecessor and go right (larger keys). - Otherwise, record
currentas the new best successor and go left (smaller keys).
At the end, compute distances from both candidates and return the minimum. If neither was found, return -1.
Correctness
The invariant maintained throughout is: the treap for letter c contains exactly { j : buf[j] == c }.
- Init: every position is registered into its letter's treap.
append: the new position is inserted into the new character's treap before the next operation runs.update: the position is erased from the old letter's treap and inserted into the new one. A no-op update (same character) skips both steps, leaving the structure unchanged.
The BST ordering ensures the predecessor/successor walk finds the true closest occurrences. Heap ordering on priorities only affects tree shape, not key order, so correctness is independent of hash quality.
Edge cases
| Situation | Behaviour |
|---|---|
target sits exactly at index | Predecessor test uses <=, so current == index is recorded; distance is 0. |
target absent | Both candidates stay -1; function returns -1. |
No-op update | Guarded by if old != ch; returns None with no structural change. |
| Equidistant left and right | min of the two distances returns the shared value. |
Query immediately after append | New position is registered before the loop moves on, so it is visible. |
Complexity
| Operation | Time | Space |
|---|---|---|
| Initialisation | O(N log N) expected | O(N) |
append | O(log N) expected | O(1) amortised |
update | O(log N) expected | O(1) |
closest | O(log N) expected | O(1) |
Overall space is O(N) for the buffer and the four flat arrays (left, right, priority, roots).
Recursion depth equals the treap height, which is O(log N) in expectation, well within Python's default limit for N ≤ 2·10^5.
Full solution
from typing import List, Optional
def live_char_store(s: str, operations: List[str], arguments: List[List]) -> List[Optional[int]]:
# 26 treap roots, one per lowercase letter.
# Node ids ARE the buffer positions, so one set of flat arrays backs all 26 trees.
roots = [-1] * 26
left = []
right = []
priority = []
def _priority(index: int) -> int:
# Knuth multiplicative hash — scrambles sequential indices so the
# treap stays balanced even when positions are inserted in order.
return ((index + 1) * 2654435761) & 0xFFFFFFFF
def split(root: int, key: int):
"""Split into (keys < key, keys >= key)."""
if root == -1:
return -1, -1
if root < key:
a, b = split(right[root], key)
right[root] = a
return root, b
a, b = split(left[root], key)
left[root] = b
return a, root
def merge(a: int, b: int) -> int:
"""Merge two treaps where every key in a < every key in b."""
if a == -1:
return b
if b == -1:
return a
if priority[a] > priority[b]:
right[a] = merge(right[a], b)
return a
left[b] = merge(a, left[b])
return b
def insert(root: int, node: int) -> int:
if root == -1:
return node
if priority[node] > priority[root]:
a, b = split(root, node)
left[node] = a
right[node] = b
return node
if node < root:
left[root] = insert(left[root], node)
else:
right[root] = insert(right[root], node)
return root
def erase(root: int, key: int) -> int:
if root == key:
return merge(left[root], right[root])
if key < root:
left[root] = erase(left[root], key)
else:
right[root] = erase(right[root], key)
return root
def register(index: int, ch: str) -> None:
"""Grow the node arrays if needed, then insert index into ch's treap."""
while len(left) <= index:
idx = len(left)
left.append(-1)
right.append(-1)
priority.append(_priority(idx))
left[index] = right[index] = -1
code = ord(ch) - 97
roots[code] = insert(roots[code], index)
# Build treaps from the initial string.
for i, ch in enumerate(s):
register(i, ch)
buf = list(s)
results: List[Optional[int]] = []
for op, args in zip(operations, arguments):
if op == "append":
ch = args[0]
idx = len(buf)
buf.append(ch)
register(idx, ch)
results.append(None)
elif op == "update":
idx, ch = args
old = buf[idx]
if old != ch:
roots[ord(old) - 97] = erase(roots[ord(old) - 97], idx)
roots[ord(ch) - 97] = insert(roots[ord(ch) - 97], idx)
buf[idx] = ch
results.append(None)
else: # "closest"
idx, target = args
current = roots[ord(target) - 97]
predecessor = -1 # largest position <= idx
successor = -1 # smallest position > idx
while current != -1:
if current <= idx:
predecessor = current
current = right[current]
else:
successor = current
current = left[current]
best = None
if predecessor != -1:
best = idx - predecessor
if successor != -1:
d = successor - idx
best = d if best is None else min(best, d)
results.append(-1 if best is None else best)
return results