Three Mini Simulations: Case Folding, Aligned Allocator, Run Counter
Data Structure DesignAuto-graded · 25 test casesLast updated
Solve three independent simulations: case-insensitive adjacent changes, an 8-aligned memory allocator, and online counting of same-color runs on a line.
You are given four batches of independent test scenarios. Process each batch and return all the results together in one dictionary.
Task A: Case-blind neighbor changes
For each string in texts, count the indices i (with 0 <= i < len(s) - 1) where s[i].lower() != s[i + 1].lower(). Strings with fewer than two characters give 0. Characters that are not letters are compared as they are.
Task B: Aligned memory allocator
The k-th entry of initial_memories is a 0/1 array describing a memory of n cells (0 = free, 1 = occupied). The k-th entry of memory_ops is the list of operations to run, in order, on that memory. Each scenario starts fresh.
Each operation is a two-element list [code, value]:
-
[0, size](allocate). Find the smallest start indexssuch thats % 8 == 0,s + size <= n, and all cellss .. s+size-1are currently free. If one exists:- Mark those cells occupied under a new allocation ID.
- IDs are numbered
1, 2, 3, ...in order of successful allocations. A failed allocation does not use up an ID. - Output
[s, id].
If none exists, or if
size < 0, output[-1, -1]. A request withsize == 0is valid: it succeeds at start0, takes an ID, and occupies no cells. -
[1, id](erase). Ifidbelongs to an allocation that is still live, free exactly the cells of that allocation and outputTrue. Otherwise (unknown ID, or already erased) outputFalse.
Cells that are 1 in the initial array stay occupied forever and belong to no ID. Freed cells can be reused immediately.
Task C: Counting runs of equal color
Each entry of color_updates is a separate timeline of updates [position, color], applied in order to an initially empty line. An update sets the color at integer position, either coloring a new position or overwriting an existing one.
After each update, output the number of runs. A run is a maximal group of consecutive integer positions that are all colored with the same color. Positions with no color are not part of any run and break continuity. Positions may be negative or large.
Output
Return a dictionary with exactly these keys:
"adjacent_counts": one integer per string intexts."allocator_results": one list per memory scenario, containing one result per operation ([start, id]pairs or booleans, as described above)."segment_counts": one list per timeline incolor_updates, containing the run count after each update.
Constraints
- Any of the four input lists may be empty. The output lists have matching lengths.
len(initial_memories) == len(memory_ops).- Each memory has length
0 <= n <= 5000and contains only0and1. - Allocation sizes and erase IDs are integers (sizes may be
0or negative). - Total number of operations and updates across all scenarios is at most
10^4. - Positions and colors are integers. Positions fit in 64-bit signed integers.
- String lengths are at most
10^5.
Examples
Example 1
Input: run_three_simulations([], [[0, 0]], [[[0, 3], [0, 2], [1, 1], [1, 2]]], [[[1, 7], [2, 7], [3, 7], [2, 8], [2, 7]]])
Output: {'adjacent_counts': [], 'allocator_results': [[[-1, -1], [0, 1], True, False]], 'segment_counts': [[1, 1, 1, 3, 1]]}
Example 2
Input: run_three_simulations([], [[1, 1]], [[[0, 1], [1, 1]]], [[[0, 1], [2, 1], [1, 1]]])
Output: {'adjacent_counts': [], 'allocator_results': [[[-1, -1], False]], 'segment_counts': [[1, 2, 1]]}
Hints
Hint 1
Task A needs one pass over neighboring pairs; lowercase both characters before comparing.
Hint 2
For Task B, keep a map from live ID to the cells it owns. Try starts 0, 8, 16, ... in order and check that the whole block is free. Only increase the ID counter when an allocation succeeds.
Hint 3
For Task C, an update can only change the runs touching its own position. Remove the old point's contribution to the count, then add the new point's contribution, looking only at the neighbors at position-1 and position+1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The three tasks are independent, so each is solved separately and the results are put in the dictionary.
Task A
Walk over every neighboring pair of characters and count those that differ after lowercasing. Strings shorter than two characters have no pairs, so they give 0.
Task B
Keep two things per scenario: the cell array and a dictionary from live ID to the list of cells it owns.
- Allocate: if
size < 0, fail. Otherwise try starts0, 8, 16, ...up ton - size, in increasing order, and take the first start whose whole block is free. Because starts are tried in increasing order, the first success is the leftmost valid one. On success, record the cells under the new ID, mark them occupied, and advance the ID counter. On failure, output[-1, -1]and leave the counter alone. Withsize == 0the empty block is trivially free, so start0is chosen. - Erase: if the ID is not in the live dictionary, it was never issued or was already erased, so output
False. Otherwise reset exactly its recorded cells to free, remove it from the dictionary, and outputTrue. Cells that were occupied initially are never in any record, so they are never freed.
Task C
Maintain a dictionary position -> color and the current run count. An update at p only affects runs that include p, and the only neighbors that matter are p-1 and p+1.
- If
palready has a colorold, remove it. The run count drops by 1, but each neighbor with coloroldkeeps its own run alive, so add 1 for each such neighbor. (A point in the middle of a run splits it in two, giving a net +1.) - Insert the new color. Look at the two neighbors:
- Both have the new color: two runs merge with the new point, so subtract 1.
- Neither has it: the point starts a new run, so add 1.
- Exactly one has it: the point extends a run, so the count is unchanged.
- Store the color and record the count.
Recoloring a point to the color it already has removes and re-adds it with no net change, as required. Missing positions are never equal to any color, so gaps break runs.
Complexity
- Task A: O(total length of all strings) time, O(1) extra space per string.
- Task B: an allocation checks up to n/8 starts, each costing up to
sizecell checks, so it is O(n·size/8) per call. Erase costs O(size). Space is O(n) per scenario. - Task C: O(1) expected time per update with hash map lookups. Space is O(number of distinct colored positions).
Reference solution
from typing import Dict, List
def run_three_simulations(texts, initial_memories, memory_ops, color_updates):
adjacent_counts = [
sum(a.lower() != b.lower() for a, b in zip(s, s[1:]))
for s in texts
]
allocator_results = []
for initial, ops in zip(initial_memories, memory_ops):
cells = list(initial)
live = {}
next_id = 1
out = []
for code, value in ops:
if code == 0:
size = value
found = False
if size >= 0:
for start in range(0, len(cells) - size + 1, 8):
if all(cells[i] == 0 for i in range(start, start + size)):
live[next_id] = list(range(start, start + size))
for i in live[next_id]:
cells[i] = next_id + 1
out.append([start, next_id])
next_id += 1
found = True
break
if not found:
out.append([-1, -1])
else:
if value not in live:
out.append(False)
else:
for i in live.pop(value):
cells[i] = 0
out.append(True)
allocator_results.append(out)
segment_results = []
missing = object()
for updates in color_updates:
colors = {}
runs = 0
out = []
for position, color in updates:
if position in colors:
old = colors[position]
runs -= 1
if colors.get(position - 1, missing) == old:
runs += 1
if colors.get(position + 1, missing) == old:
runs += 1
left = colors.get(position - 1, missing)
right = colors.get(position + 1, missing)
if left == color and right == color:
runs -= 1
elif left != color and right != color:
runs += 1
colors[position] = color
out.append(runs)
segment_results.append(out)
return {
"adjacent_counts": adjacent_counts,
"allocator_results": allocator_results,
"segment_counts": segment_results,
}