Three-Problem Algorithmic Challenge Set
Arrays & HashingModel answerLast updated
Solve three independent problems: tournament match counting, grid traversal with movement commands, and finding maximum sum of digit-disjoint pairs.
You have 150 minutes to solve three independent coding problems. Each problem stands alone with its own input and output.
Problem 1: Tournament Match Participation
You have $n$ competitors arranged in sequence, numbered $1$ through $n$. Each competitor $i$ possesses a unique strength level $a[i]$, where the values form a permutation of $1$ to $n$.
The tournament operates in elimination rounds:
- Each round pairs adjacent survivors: position $1$ faces $2$, position $3$ faces $4$, etc.
- Within each pairing, the competitor with greater strength advances; the weaker one is eliminated.
- Winners maintain their relative ordering and form the lineup for the subsequent round.
- This continues until a single champion remains.
For each original competitor $i$, compute $b[i]$ = the total number of matches competitor $i$ fought before elimination (or through championship).
Input: Integer $n$ (a power of 2, $1 \le n \le 200{,}000$) and array $a[1..n]$ (a permutation of $1..n$).
Output: Array $b[1..n]$ where $b[i]$ is the match count for competitor $i$.
Problem 2: Grid Navigation Instructions
You control a robot on an $R \times C$ grid ($3 \le R, C \le 50$) where:
#= impassable wall.= traversable floor*= robot's starting position (also traversable)
The perimeter is entirely walls. All floor cells (including *) form one connected region.
Generate a sequence of movement commands (^ up, v down, < left, > right) for each scenario below. Every move must keep the robot on floor cells. The sequence may be at most $100{,}000$ characters. You need not return to start.
Five Scenarios:
-
Perimeter only: Floor cells form a solid rectangle. Start is the top-left corner. Visit every perimeter cell exactly once; never enter interior cells.
-
Full rectangle: Floor cells form a solid rectangle. Start anywhere inside. Visit every floor cell at least once.
-
Two-room corridor: Two separate rectangular regions connected by exactly one corridor cell. Start anywhere. Visit all floor cells.
-
Linear path: Floor cells form a path with no branches. Start anywhere on the path. Visit every cell.
-
General shape: Any connected floor region. Start anywhere. Visit every floor cell.
Output: For each scenario, provide one valid command string meeting the requirements, length $\le 100{,}000$.
Problem 3: Digit-Disjoint Maximum Pair Sum
Given an array of $n$ non-negative integers $a[1..n]$ ($1 \le n \le 200{,}000$, each $a[i] \le 10^9$).
Two numbers have disjoint digits if their decimal representations share no common digit. For example, $123$ and $4560$ are disjoint; $15$ and $51$ are not (both contain $1$ and $5$).
Task: Find two distinct indices $i \ne j$ where $a[i]$ and $a[j]$ have disjoint digits, maximizing $a[i] + a[j]$. Return this maximum sum, or $-1$ if no valid pair exists.
Input: Array $a[1..n]$.
Output: Maximum sum of a valid pair, or $-1$ if impossible.
Hints
Hint 1
For the tournament, think about how many rounds each competitor survives rather than simulating individual matchups.
Hint 2
Grid traversal can use depth-first search with backtracking—each edge traversed twice (forward and return) gives a tight bound.
Hint 3
Represent each number's digit set as a 10-bit mask; you only need to track the maximum value for each unique mask.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Problem 1: Tournament Match Participation
Approach:
Each competitor plays exactly one match per round they remain active. The key insight: simulate the tournament round-by-round, tracking which competitors advance and incrementing their match counts.
Algorithm:
- Initialize
matches[i] = 0for all competitors. - Maintain a list of active competitors (initially all $n$).
- Each round:
- Pair adjacent active competitors
- For each pair, both increment their match count
- Winner (higher strength) advances to next round's active list
- Repeat until one competitor remains.
Complexity: Each round processes $n/2^k$ competitors in round $k$. Total work: $\sum_{k=0}^{\log n - 1} n/2^k = O(n)$ comparisons plus array operations = $O(n \log n)$ overall.
Code:
def tournament_matches(n, a):
matches = [0] * n
active = list(range(n)) # indices of active competitors
while len(active) > 1:
next_round = []
for i in range(0, len(active), 2):
idx1, idx2 = active[i], active[i+1]
matches[idx1] += 1
matches[idx2] += 1
# Higher strength wins
if a[idx1] > a[idx2]:
next_round.append(idx1)
else:
next_round.append(idx2)
active = next_round
return matches
Edge cases: When $n = 1$, the single competitor plays 0 matches (already champion).
Problem 2: Grid Navigation Instructions
Approach:
For scenarios 2-5, use DFS-based Euler tour: traverse a spanning tree of floor cells, visiting each edge twice (once forward, once backtracking). This guarantees visiting all cells with exactly $2(V-1)$ moves for $V$ floor cells.
For scenario 1 (perimeter only), explicitly walk the rectangle's border.
Algorithm (scenarios 2-5):
- Build adjacency graph of floor cells
- DFS from start, maintaining visited set
- When moving to unvisited neighbor: append direction, recurse, append reverse direction
- Result: visit all cells with length $\le 2(V-1) \le 2 \cdot 50 \cdot 50 = 5000 \ll 100{,}000$
Algorithm (scenario 1): Walk clockwise around perimeter: right along top edge, down right edge, left along bottom, up left edge.
Code (general coverage):
def generate_path(grid):
R, C = len(grid), len(grid[0])
start = None
for r in range(R):
for c in range(C):
if grid[r][c] == '*':
start = (r, c)
directions = {'^': (-1,0), 'v': (1,0), '<': (0,-1), '>': (0,1)}
reverse = {'^': 'v', 'v': '^', '<': '>', '>': '<'}
visited = set()
path = []
def dfs(r, c):
visited.add((r, c))
for symbol, (dr, dc) in directions.items():
nr, nc = r + dr, c + dc
if (0 <= nr < R and 0 <= nc < C and
grid[nr][nc] != '#' and (nr, nc) not in visited):
path.append(symbol)
dfs(nr, nc)
path.append(reverse[symbol])
dfs(*start)
return ''.join(path)
Complexity: $O(RC)$ time and space. Move count = $2(V-1)$ where $V \le RC$.
Problem 3: Digit-Disjoint Maximum Pair Sum
Approach:
Convert each number to a 10-bit mask representing which digits (0-9) appear. Two numbers are disjoint if their masks have no common bits set.
Optimization: Since we only care about maximums, keep only the largest value for each unique mask (at most 1024 masks). Then check all mask pairs for disjointness.
Algorithm:
- For each number, compute its digit mask
- Store only
max_val[mask]= maximum number with that mask - Check all pairs of masks: if
mask1 & mask2 == 0, considermax_val[mask1] + max_val[mask2] - Return maximum sum found, or $-1$ if no valid pair
Code:
def max_disjoint_sum(a):
def digit_mask(num):
mask = 0
for digit in str(num):
mask |= (1 << int(digit))
return mask
# Keep max value per mask
max_val = {}
for num in a:
mask = digit_mask(num)
max_val[mask] = max(max_val.get(mask, 0), num)
masks = list(max_val.keys())
result = -1
# Check all mask pairs
for i in range(len(masks)):
for j in range(i+1, len(masks)):
if masks[i] & masks[j] == 0: # Disjoint
result = max(result, max_val[masks[i]] + max_val[masks[j]])
return result
Complexity: $O(n \cdot d + M^2)$ where $d$ is average digit count ($\le 10$) and $M \le 1024$ is distinct masks. Effectively $O(n + 2^{20})$ worst case, but typically much faster.
Alternative: Use sum-over-subsets DP to find maximum complement in $O(10 \cdot 2^{10})$ after preprocessing.
Edge cases: If $n = 1$ or all numbers share at least one digit with every other number, return $-1$.
Common Pitfalls
- Problem 1: Forgetting the champion plays $\log_2 n$ matches, not $\log_2 n - 1$.
- Problem 2: Generating moves without backtracking leads to exponential length; not checking bounds/walls causes invalid moves.
- Problem 3: Comparing all $O(n^2)$ pairs times out; not handling the case where a number appears multiple times with the same mask (keep only the max).