Peak Subarray, Lone Value, and Spiral Grid Traversal
Arrays & HashingAuto-graded · 23 test casesLast updated
Tests Kadane's algorithm with tie-breaking, frequency-based minimum selection, and counterclockwise skip-step grid simulation in one combined function.
Problem
You will implement a single function that solves three independent sub-problems and returns their answers together in a dictionary.
Sub-problem 1 — Peak Contiguous Subarray
Given an integer array nums, find the contiguous subarray whose elements sum to the largest possible value.
Return [max_sum, start, end] where start and end are zero-based, inclusive indices of the winning subarray.
Tie-breaking rules (apply in order):
- If two subarrays share the same sum, prefer the one with fewer elements (shorter length).
- If they still tie on length, prefer the one whose
startindex is smaller (appears earlier).
Your solution must run in O(n) time and use O(1) extra space.
When every element is negative, the answer is the single element with the largest (least-negative) value, at its first occurrence.
Sub-problem 2 — Minimum Singleton Value
Given the same array nums, find the smallest integer that appears exactly once.
- If several values each appear exactly once, return the smallest among them.
- If no value appears exactly once, return
-1.
Sub-problem 3 — Counterclockwise Skip-Step Grid
You are on an m × n grid. Rows and columns are numbered starting from 1, with (1, 1) at the top-left. You begin at (1, 1).
You move through a repeating direction cycle: right → up → left → down → right → …
On each attempt you jump exactly two cells in the current direction (you skip the intermediate cell, which remains unvisited). A jump is valid only if the landing cell is within the grid boundaries and has not been visited before. The skipped cell's visited status is irrelevant.
When the next jump in the current direction would be invalid (out of bounds or already visited), rotate 90° counterclockwise to the next direction and try again. If all four directions are blocked, stop immediately.
Return [row, col] — the one-based coordinates of the last cell you successfully landed on.
Return value
Return a single dictionary with exactly these keys:
{
"max_subarray": [max_sum, start_index, end_index],
"min_unique": <integer or -1>,
"last_grid_cell": [row, col]
}
Constraints
1 <= len(nums) <= 10^5-10^4 <= nums[i] <= 10^41 <= m, n <= 100- The grid always has at least one cell;
(1, 1)is always visited and is the answer when no valid jump exists from the start. numsis used for both sub-problems 1 and 2.
Examples
Example 1
Input: combined_array_grid_challenge([-2, 1, -3, 4, -1, 2, 1, -5, 4], 3, 4)
Output: {'max_subarray': [6, 3, 6], 'min_unique': -5, 'last_grid_cell': [3, 1]}
Example 2
Input: combined_array_grid_challenge([-8, -3, -3, -5], 1, 1)
Output: {'max_subarray': [-3, 1, 1], 'min_unique': -8, 'last_grid_cell': [1, 1]}
Example 3
Input: combined_array_grid_challenge([2, 2, 1, 3, 3, -4], 3, 3)
Output: {'max_subarray': [11, 0, 4], 'min_unique': -4, 'last_grid_cell': [3, 1]}
Hints
Hint 1
For the subarray problem, think about when restarting from the current index strictly improves your candidate versus extending the existing one — the restart condition on zero is what enforces the shortest-length tie-break automatically.
Hint 2
For the singleton minimum, a single pass to build a frequency map followed by a filtered minimum is all you need; watch out for the case where -1 itself is a valid answer (the sentinel is still correct per the spec, but worth noting).
Hint 3
For the grid, every jump moves by exactly 2 in one coordinate, so you can only ever land on cells where both the row and column are odd — you are effectively walking a compressed ceil(m/2) × ceil(n/2) grid with unit steps, which bounds the total number of moves.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sub-problem 1 — Peak Contiguous Subarray
The algorithm is a variant of Kadane's. At each index i we decide whether to extend the running subarray or restart from i alone.
The restart condition is current_sum <= 0 (not strictly negative). This is the key tie-breaking detail: if the running sum has dropped to zero, extending it versus restarting produces the same future sum, but restarting yields a strictly shorter subarray. Choosing to restart encodes the "prefer shorter" rule automatically, without any special-case logic.
When updating the global best we apply the three comparisons in order: better sum wins, then shorter length wins, then earlier start wins. Because i always increases, the earliest-start tie-break is never triggered in practice (a later candidate with the same sum and length can never have a smaller start), but the guard is included for correctness.
All-negative inputs are handled without a special case. Every step restarts, so each candidate is a single element; the maximum element wins at its first occurrence.
Correctness sketch: among all subarrays ending at index i, the one tracked by current_sum/current_start is the one with the highest sum and, among those tied on sum, the shortest length. The proof is by induction on i using the restart condition. The global best across all i is therefore exactly the required answer.
Complexity: O(n) time, O(1) extra space.
Sub-problem 2 — Minimum Singleton Value
Build a frequency map in one pass, then filter to keys with count exactly 1, then take the minimum. Python's built-in min over an empty sequence is guarded by the conditional.
Complexity: O(n) time, O(k) space where k is the number of distinct values.
Sub-problem 3 — Counterclockwise Skip-Step Grid Walk
Because every jump moves by exactly 2 in one coordinate, the parity of each coordinate is preserved. Starting from (1, 1) (both odd), every reachable cell has both an odd row and an odd column. There are at most ceil(m/2) × ceil(n/2) such cells, which bounds the walk length.
The simulation maintains a visited set and a counter of how many consecutive directions have been blocked. When that counter reaches 4 (all directions tried without a valid move) the loop exits. On a valid move the counter resets to zero.
Complexity: O(m × n) time (bounded by the number of reachable cells times the constant 4 direction checks per move), O(m × n) space for the visited set (at most ceil(m/2) × ceil(n/2) entries).
Full Reference Solution
from typing import Dict, List
def combined_array_grid_challenge(nums: List[int], m: int, n: int) -> Dict[str, object]:
# ------------------------------------------------------------------
# Sub-problem 1: Peak contiguous subarray (Kadane's with tie-breaking)
# ------------------------------------------------------------------
best_sum = None
best_start = best_end = 0
current_sum = 0
current_start = 0
for i, value in enumerate(nums):
if i == 0 or current_sum <= 0:
current_sum = value
current_start = i
else:
current_sum += value
current_length = i - current_start + 1
best_length = best_end - best_start + 1
if (best_sum is None
or current_sum > best_sum
or (current_sum == best_sum and current_length < best_length)
or (current_sum == best_sum
and current_length == best_length
and current_start < best_start)):
best_sum = current_sum
best_start = current_start
best_end = i
# ------------------------------------------------------------------
# Sub-problem 2: Minimum value with frequency exactly 1
# ------------------------------------------------------------------
counts: Dict[int, int] = {}
for value in nums:
counts[value] = counts.get(value, 0) + 1
singleton_values = [v for v, c in counts.items() if c == 1]
min_singleton = min(singleton_values) if singleton_values else -1
# ------------------------------------------------------------------
# Sub-problem 3: Counterclockwise skip-step grid walk
# ------------------------------------------------------------------
directions = [(0, 1), (-1, 0), (0, -1), (1, 0)] # right, up, left, down
row, col = 1, 1
visited = {(row, col)}
direction = 0
consecutive_blocks = 0
while consecutive_blocks < 4:
dr, dc = directions[direction]
next_row = row + 2 * dr
next_col = col + 2 * dc
if (1 <= next_row <= m
and 1 <= next_col <= n
and (next_row, next_col) not in visited):
row, col = next_row, next_col
visited.add((row, col))
consecutive_blocks = 0
else:
direction = (direction + 1) % 4
consecutive_blocks += 1
return {
"max_subarray": [best_sum, best_start, best_end],
"min_unique": min_singleton,
"last_grid_cell": [row, col],
}