Solving Multi-Task Online Assessment Challenges
Arrays & HashingModel answerLast updated
A guide to solving four standard assessment tasks: cumulative running totals, step-by-step array reduction, deterministic matrix block placement, and linear arithmetic series optimization.
You are tasked with implementing four independent algorithmic modules often found in technical screen assessments.
Task 1: Milestone Day Identification
Given an array traffic where traffic[i] denotes the daily visitors to a service on day i (0-indexed), and a target integer threshold, determine the earliest day index i on which the cumulative sum of visitors from day 0 up to day i becomes greater than or equal to threshold.
- If the total standard visitor traffic never meets or exceeds
threshold, return-1.
Task 2: Linear Subtraction Algorithm Simulation
Given an array of non-negative integers values, simulate the operation below and compute the accumulated sum total_reduced:
- Set
total_reduced = 0. - Locate the first entry in
valuesfrom left to right that is strictly greater than0. Call this valuex. If no such element exists, terminate and returntotal_reduced. - Starting from the index where
xwas found, iterate towards the end of the array:- If an element is strictly less than
x, stop the rightward scan immediately. - Otherwise, subtract
xfrom the element and continue to the next position on the right.
- If an element is strictly less than
- Add
xtototal_reduced. - Repeat from Step 2.
Return total_reduced after all valid rounds are processed.
Task 3: Priority Tetronimo Grid Placement
You are given a matrix grid of dimensions rows x cols initially filled with empty markers '.'. You are also given an ordered list of block identifiers placement_order containing characters from {A, B, C, D, E}. Each character corresponds to a relative shape defined by offsets relative to its top-left bounding anchor coordinate (0, 0).
For each block in placement_order, find the first available coordinate (r, c) in row-major order (smallest row index r, then smallest column index c) such that placing the block's anchor at (r, c) allows all associated shape cells to fit entirely within the grid bounds and on unoccupied ('.') positions.
Place each block without rotation. Once placed, label those grid positions with the block's character. Assume all inputs guarantee that every block in placement_order has at least one valid fitting position.
Return the final 2D array representation of the grid.
Task 4: Minimum Operations for Uniform Linear Slopes
You are given an array elevations of size N, representing the height of structures along a avenue. In a single modification step, you can increase the height of any individual structure by 1.
A configuration is valid if its heights follow one of two continuous unit-step arithmetic progressions across all indices i ($0 \le i < N$):
- Strictly Ascending: $H[i] = k + i$ for some integer $k$.
- Strictly Descending: $H[i] = k - i$ for some integer $k$.
Because you can only perform height additions (you cannot decrease any height), find the minimum total number of unit increments required to adjust elevations into either a valid Strictly Ascending or valid Strictly Descending structure sequence.
Hints
Hint 1
For Task 1, iterate through the array once while keeping a running sum.
Hint 2
For Task 2, notice that elements never increase and zero values can be safely bypassed; tracking the current scan start index prevents redundant scanning.
Hint 3
For Task 4, express target heights as functions of a single starting value k. Find the lower bound for k forced by the condition target[i] >= elevations[i].
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview & Solutions
Here are detailed solutions for each of the four components.
Task 1: Milestone Day Identification
Approach
Maintain a running total as you traverse traffic. The first index i where running_total >= threshold is your target index. If the loop completes without meeting the threshold, return -1.
Complexity
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the number of days.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space.
def find_milestone_day(traffic: list[int], threshold: int) -> int:
current_sum = 0
for day, count in enumerate(traffic):
current_sum += count
if current_sum >= threshold:
return day
return -1
Task 2: Linear Subtraction Simulation
Approach
Because values can only decrease and zeroes remain zero, the index of the first positive value strictly moves to the right. We maintain a pointer start_idx to track where to begin looking for x. In each pass:
- Advance
start_idxto the first non-zero entry. - Read
x = values[start_idx]. - Subtract
xfrom contiguous elements starting atstart_idxuntil an element $< x$ is encountered. - Add
xtototal_reduced.
Complexity
- Time Complexity: $\mathcal{O}(N^2)$ in the worst case (e.g., descending sequences), which easily runs within time limits for typical array bounds ($N \le 1000$).
- Space Complexity: $\mathcal{O}(N)$ if creating a mutable copy of the input, $\mathcal{O}(1)$ extra space otherwise.
def simulate_subtractions(values: list[int]) -> int:
arr = list(values)
n = len(arr)
total_reduced = 0
start_idx = 0
while True:
# Step 1: Find first positive element
while start_idx < n and arr[start_idx] == 0:
start_idx += 1
if start_idx == n:
break
x = arr[start_idx]
# Step 2: Continuous reduction scan
curr = start_idx
while curr < n and arr[curr] >= x:
arr[curr] -= x
curr += 1
total_reduced += x
return total_reduced
Task 3: Priority Tetronimo Grid Placement
Approach
- Normalize shape coordinates so that the minimum row and column offsets are
0. - For each block in
placement_order, scan the grid in row-major order (top to bottom, left to right). - Check if all offsets for the block relative to grid position
(r, c)fall within grid bounds and land on'.'. - The first position
(r, c)that satisfies these conditions is selected greedily. Update the grid cells with the block's identifier and proceed to the next block.
Complexity
- Time Complexity: $\mathcal{O}(B \times R \times C \times S)$, where $B$ is the number of blocks, $R \times C$ is the grid size, and $S$ is the maximum cells in a shape.
- Space Complexity: $\mathcal{O}(R \times C)$ to store the grid.
def place_tetronimos(
rows: int,
cols: int,
placement_order: list[str],
shapes: dict[str, list[tuple[int, int]]]
) -> list[list[str]]:
grid = [['.'] * cols for _ in range(rows)]
# Normalize shapes relative to (0, 0) top-left anchor
normalized_shapes = {}
for b_id, cells in shapes.items():
min_r = min(r for r, c in cells)
min_c = min(c for r, c in cells)
normalized_shapes[b_id] = [(r - min_r, c - min_c) for r, c in cells]
for b_id in placement_order:
offsets = normalized_shapes[b_id]
placed = False
for r in range(rows):
for c in range(cols):
# Check validity
can_place = True
for dr, dc in offsets:
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols) or grid[nr][nc] != '.':
can_place = False
break
if can_place:
for dr, dc in offsets:
grid[r + dr][c + dc] = b_id
placed = True
break
if placed:
break
return grid
Task 4: Minimum Operations for Uniform Linear Slopes
Mathematical Formulation
Ascending Pattern: We want $H[i] = k + i$. Since we can only increment elements ($H[i] \ge \text{elevations}[i]$): $$k + i \ge \text{elevations}[i] \implies k \ge \text{elevations}[i] - i$$
To ensure all elements satisfy this condition, we set: $$k_{asc} = \max_{0 \le i < N} (\text{elevations}[i] - i)$$ The cost for the ascending sequence is: $$\text{Cost}{asc} = \sum{i=0}^{N-1} (k_{asc} + i - \text{elevations}[i])$$
Descending Pattern: We want $H[i] = k - i$. Similarly: $$k - i \ge \text{elevations}[i] \implies k \ge \text{elevations}[i] + i$$
To satisfy this for all elements: $$k_{desc} = \max_{0 \le i < N} (\text{elevations}[i] + i)$$ The cost for the descending sequence is: $$\text{Cost}{desc} = \sum{i=0}^{N-1} (k_{desc} - i - \text{elevations}[i])$$
The overall minimum operation count is $\min(\text{Cost}{asc}, \text{Cost}{desc})$.
Complexity
- Time Complexity: $\mathcal{O}(N)$ requiring a single linear pass over the elevations array.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space.
def min_operations_beautiful_street(elevations: list[int]) -> int:
if not elevations:
return 0
n = len(elevations)
# 1. Calculate best parameter k for ascending sequence
max_k_asc = max(h - i for i, h in enumerate(elevations))
cost_asc = sum((max_k_asc + i) - h for i, h in enumerate(elevations))
# 2. Calculate best parameter k for descending sequence
max_k_desc = max(h + i for i, h in enumerate(elevations))
cost_desc = sum((max_k_desc - i) - h for i, h in enumerate(elevations))
return min(cost_asc, cost_desc)