RLE Vector Dot Product and Execution Log Processor
Data Structure DesignAuto-graded · 22 test casesLast updated
Compress sparse sequences into run-length encodings, calculate their dot product, and analyze nested call timestamps using a call stack.
Implement a dual-task utility that performs run-length encoding operations on dense integer sequences and evaluates exclusive function execution durations from structured event traces.
Task 1: Compressed Dot Product
- Given two integer lists
aandbof equal total length, convert each into its run-length encoded (RLE) form: consecutive identical values are grouped into pairs[value, count]. - Compute the dot product $\sum a[i] \cdot b[i]$ using only the generated run-length representations (without rebuilding the original uncompressed lists).
Task 2: Exclusive Call Duration
Given $n$ functions indexed $0$ through $n-1$ operating on a single-threaded system, process a chronological sequence of event log strings formatted as standard "<function_id>:<event_type>:<timestamp>".
event_typecan be"start"or"end".- Functions may call other functions recursively or sequentially.
- Duration is calculated exclusively (time spent inside child calls is excluded from the parent function's runtime).
- A
"start"log at time $t$ indicates execution begins at the start of time step $t$. - An
"end"log at time $t$ indicates execution continues through the end of time step $t$ (inclusive).
Return a dictionary containing four keys:
"compressed_a": RLE form ofaas a list of[value, count]pairs."compressed_b": RLE form ofbas a list of[value, count]pairs."dot_product": The computed dot product integer."exclusive_times": A list of length $n$ containing the net exclusive execution units for each function ID from $0$ to $n-1$.
Constraints
- $1 \le \text{len}(a) = \text{len}(b) \le 10^7$
- Values in $a$ and $b$ fit in signed 32-bit integers.
- $0 \le \text{function_id} < n \le 10^4$
- $0 \le \text{timestamp} \le 10^9$
- Timestamps in
logsare well-formed, non-decreasing, and correctly balanced.
Examples
Example 1
Input: optimize_vectors_and_exclusive_times([1, 1, 1, 2, 2], [3, 3, 4, 4, 4], 2, ['0:start:0', '1:start:2', '1:end:5', '0:end:6'])
Output: {'compressed_a': [[1, 3], [2, 2]], 'compressed_b': [[3, 2], [4, 3]], 'dot_product': 26, 'exclusive_times': [3, 4]}
Example 2
Input: optimize_vectors_and_exclusive_times([0, 0, 0, 5, 5, -1], [2, 2, 3, 3, 3, -4], 3, ['0:start:0', '0:end:0', '1:start:2', '2:start:3', '2:end:4', '1:end:5'])
Output: {'compressed_a': [[0, 3], [5, 2], [-1, 1]], 'compressed_b': [[2, 2], [3, 3], [-4, 1]], 'dot_product': 34, 'exclusive_times': [1, 2, 2]}
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Overview
This task combines two fundamental state-tracking techniques:
-
Run-Length Encoding & Two-Pointer Aggregation:
- Compressing arrays requires iterating through each sequence once, grouping adjacent identical values into
[value, count]sublists. - Finding the dot product from two RLE lists relies on a two-pointer scan over the compressed structures. At each step, take the minimum of the remaining span counts from both lists, add
val_a * val_b * min_spanto the dot product, decrement both remaining spans, and advance the respective pointer whenever a span is exhausted.
- Compressing arrays requires iterating through each sequence once, grouping adjacent identical values into
-
Call Stack State Machine for Exclusive Duration:
- Because single-threaded function calls nest, the active call is represented by the element at the top of a stack.
- Maintain a tracker
previous_time. - On
"start"attimestamp: If the stack is non-empty, credit the active functiontimestamp - previous_timeduration units. Push the new function ID onto the stack and setprevious_time = timestamp. - On
"end"attimestamp: Credit the function at the top of the stacktimestamp - previous_time + 1units (accounting for end-of-step inclusion). Pop the stack and updateprevious_time = timestamp + 1.
Complexity Analysis
- Task 1 Complexity: Compression takes $O(M)$ time where $M = \text{len}(a)$. Two-pointer dot product calculation takes $O(R_a + R_b)$ time where $R_a, R_b$ are the counts of distinct RLE blocks.
- Task 2 Complexity: Processing $L$ log entries takes $O(L)$ time using basic stack operations and string splitting.
- Overall Space Complexity: $O(R_a + R_b + N + D)$ where $D$ is the maximum call stack depth.
from typing import List, Dict
def optimize_vectors_and_exclusive_times(a: List[int], b: List[int], n: int, logs: List[str]) -> Dict[str, object]:
def compress(values: List[int]) -> List[List[int]]:
if not values:
return []
result = []
current = values[0]
count = 1
for value in values[1:]:
if value == current:
count += 1
else:
result.append([current, count])
current = value
count = 1
result.append([current, count])
return result
compressed_a = compress(a)
compressed_b = compress(b)
i = j = 0
remaining_a = compressed_a[0][1] if compressed_a else 0
remaining_b = compressed_b[0][1] if compressed_b else 0
dot_product = 0
while i < len(compressed_a) and j < len(compressed_b):
amount = min(remaining_a, remaining_b)
dot_product += compressed_a[i][0] * compressed_b[j][0] * amount
remaining_a -= amount
remaining_b -= amount
if remaining_a == 0:
i += 1
if i < len(compressed_a):
remaining_a = compressed_a[i][1]
if remaining_b == 0:
j += 1
if j < len(compressed_b):
remaining_b = compressed_b[j][1]
exclusive = [0] * n
stack = []
previous_time = 0
for entry in logs:
function_id_text, event, timestamp_text = entry.split(":")
function_id = int(function_id_text)
timestamp = int(timestamp_text)
if event == "start":
if stack:
exclusive[stack[-1]] += timestamp - previous_time
stack.append(function_id)
previous_time = timestamp
else:
exclusive[stack[-1]] += timestamp - previous_time + 1
stack.pop()
previous_time = timestamp + 1
return {
"compressed_a": compressed_a,
"compressed_b": compressed_b,
"dot_product": dot_product,
"exclusive_times": exclusive,
}