Multi-Component Data Processing Challenge
Data Structure DesignAuto-graded · 22 test casesLast updated
Tests array merging from the back, queue-based task scheduling with time slices, and price-level order matching in a simulated trading book.
You will implement three independent components in a single function that returns a dictionary with three keys.
Component 1: Merge Two Sorted Arrays
You receive two sorted arrays, arr1 and arr2. The first array contains extra space at the end (filled with zeros) to accommodate all elements from the second array. Merge arr2 into arr1 so the result is sorted in ascending order.
The number of meaningful elements in arr1 equals len(arr1) - len(arr2). The remaining positions are buffer space.
Return the merged result as merged_array in the output dictionary.
Component 2: Task Scheduler with Time Slices
Implement a round-robin task scheduler that processes a sequence of operations:
add_taskwith arguments[task_id, duration]: adds a new task to the queueexecute_nextwith arguments[time_slice]: runs the next task in queue for up totime_sliceunits
When executing a task:
- Reduce its remaining duration by the actual time run (minimum of
time_sliceand current remaining duration) - Record the result as
[task_id, remaining_duration]after execution - If the task still has remaining duration greater than zero, move it to the back of the queue
- If the queue is empty, record
None
For add_task operations, record None in the results.
Tasks execute in the order they were added (FIFO). When a task is re-queued after partial execution, it goes to the back.
Return the list of results (one per operation) as scheduler_results in the output dictionary.
Component 3: Order Book Matching
You have an order book represented as a dictionary mapping price levels to available volume: {price: volume}.
Process a list of trades, where each trade is [trade_type, price, volume]:
trade_typeis either"BUY"or"SELL"- For
"BUY"trades, consume volume starting from the lowest price level - For
"SELL"trades, consume volume starting from the highest price level
For each trade:
- Remove volume from price levels in the specified order
- When a price level's volume reaches zero, remove that level from the book
- If the trade volume exceeds available liquidity, consume what is available
The price field in each trade is not used for matching (trades consume all available levels in priority order).
Return the final state of the order book as order_book in the output dictionary.
Return Value
Return a dictionary with exactly three keys:
{
"merged_array": [...], # sorted merged array
"scheduler_results": [...], # list of results per operation
"order_book": {...} # final price-to-volume mapping
}
Constraints
- 0 ≤ len(arr2) ≤ len(arr1) ≤ 10⁴
- 0 ≤ len(operations) ≤ 10³
- 0 ≤ number of price levels ≤ 10³
- 0 ≤ len(trades) ≤ 10³
- All integers fit in 32-bit signed range
- Array elements may be negative
- Task IDs and durations are positive integers
- Price levels and volumes are positive integers
- Time slices are positive integers
Examples
Example 1
Input: process_combined_tasks([1, 3, 5, 0, 0], [2, 4], [], [], {}, {})
Output: {'merged_array': [1, 2, 3, 4, 5], 'scheduler_results': [], 'order_book': {}}
Example 2
Input: process_combined_tasks([1, 3, 5, 0, 0], [2, 4], [], [], {}, [])
Output: {'merged_array': [1, 2, 3, 4, 5], 'scheduler_results': [], 'order_book': {}}
Hints
Hint 1
For array merging, working backwards prevents overwriting unread values in the destination array.
Hint 2
Use a deque for the scheduler to get efficient removal from the front and addition to the back.
Hint 3
For order matching, sort the price levels once per trade and iterate in the appropriate direction.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines three independent algorithms into one function.
Array Merging: Since the first array has buffer space at the end, we merge from right to left. We maintain three pointers: one at the last real element of the first array, one at the last element of the second array, and one at the final position. At each step, we place the larger of the two candidates at the write position and move the corresponding pointer left. This approach ensures we never overwrite unread values.
Round-Robin Scheduler: We use a double-ended queue (deque) to maintain tasks. When adding a task, we append it to the back. When executing, we pop from the front, reduce its duration by the time slice, record the result, and re-append it to the back if it has remaining duration. This implements true FIFO round-robin behavior.
Order Book Matching: For each trade, we sort the available price levels in the appropriate order (ascending for buys, descending for sells). We then iterate through these levels, consuming volume greedily until either the trade is filled or no more liquidity exists. When a level reaches zero volume, we remove it from the dictionary.
Why It Works
The backward merge works because the write pointer is always at position i + j + 1, which keeps it ahead of the read pointer i as long as we have elements from the second array to place. This guarantees we never corrupt unread data.
The scheduler correctly implements round-robin because deque provides O(1) operations at both ends. Tasks maintain arrival order within each cycle, and partially completed tasks rejoin at the back.
The order matching is correct by construction: we always take from the best available price first, which matches the specified priority rules. Greedy consumption at each level is optimal for this matching policy.
Complexity
Time:
- Array merge: O(n + m) where n and m are the lengths of the two arrays
- Scheduler: O(k) where k is the number of operations (each operation is O(1))
- Order book: O(t × p log p) where t is the number of trades and p is the number of price levels (we sort on each trade)
Space:
- Array merge: O(n + m) for the output array
- Scheduler: O(q) where q is the maximum number of queued tasks at any time
- Order book: O(p) for the dictionary copy
from collections import deque
from typing import Dict, List
def process_combined_tasks(arr1, arr2, operations, arguments, order_book, trades):
# Component 1: Merge arrays from back to front
real_elements = len(arr1) - len(arr2)
merged = list(arr1[:real_elements]) + [0] * len(arr2)
i, j, write = real_elements - 1, len(arr2) - 1, len(arr1) - 1
while j >= 0:
if i >= 0 and merged[i] > arr2[j]:
merged[write] = merged[i]
i -= 1
else:
merged[write] = arr2[j]
j -= 1
write -= 1
# Component 2: Round-robin scheduler
task_queue = deque()
results = []
for operation, args in zip(operations, arguments):
if operation == "add_task":
task_id, duration = args
task_queue.append([task_id, duration])
results.append(None)
elif operation == "execute_next":
time_slice = args[0]
if not task_queue:
results.append(None)
continue
task_id, remaining = task_queue.popleft()
remaining -= min(time_slice, remaining)
results.append([task_id, remaining])
if remaining > 0:
task_queue.append([task_id, remaining])
else:
raise ValueError("Unknown scheduler operation")
# Component 3: Order book matching
book = dict(order_book)
for trade_type, price, volume in trades:
price_levels = sorted(book) if trade_type == "BUY" else sorted(book, reverse=True)
remaining = volume
for level in price_levels:
if remaining <= 0:
break
consumed = min(book[level], remaining)
book[level] -= consumed
remaining -= consumed
if book[level] == 0:
del book[level]
return {"merged_array": merged, "scheduler_results": results, "order_book": book}