Three-Part Coding Challenge: Justification, Wildcards, and Pathfinding
Arrays & HashingAuto-graded · 21 test casesLast updated
Evaluates text formatting with precise spacing rules, wildcard-based string validation, and grid traversal with path reconstruction.
Solve three independent algorithmic problems and return your answers in a single dictionary.
Part 1: Full-Width Text Justification
You receive a list of words and a maximum line width. Arrange the words into lines where every line has exactly max_width characters and follows full justification rules.
Line packing:
- Fit as many words as possible on each line using a greedy approach
- To determine if word at index
jfits on a line starting at indexi, check that the sum of all word lengths plus the minimum required spaces between them does not exceedmax_width - Specifically, words from index
itoj(inclusive) fit if:sum_of_word_lengths + (j - i) <= max_width, where(j - i)represents the mandatory single space before each word after the first
Line formatting:
- Last line of the output: Left-justify with single spaces between words and pad remaining space on the right
- Lines containing only one word: Left-justify (no gaps between words exist) and pad remaining space on the right
- All other lines: Distribute spaces between words as evenly as possible. If spaces cannot be divided evenly among gaps, assign extra spaces to the leftmost gaps first. Specifically, if there are
ggaps andstotal spaces, each gap getss // gspaces, and the firsts % ggaps each get one additional space
Each output line must be exactly max_width characters long.
Guaranteed:
- Each word's length is at most
max_width - At least one word exists
Return a list of formatted strings.
Part 2: Wildcard Parenthesis Validation
Given a string containing only '(', ')', and '*' characters, determine if there exists any way to interpret the wildcards such that the result is a valid balanced parenthesis sequence.
Each '*' can be interpreted as:
- An opening parenthesis
'(', or - A closing parenthesis
')', or - An empty string (effectively removed)
A balanced parenthesis sequence means:
- Every opening parenthesis has a matching closing parenthesis
- At no point while reading left-to-right does the count of closing parentheses exceed opening parentheses
- The final count of opening and closing parentheses is equal
Return True if at least one valid interpretation exists, otherwise False.
Part 3: Shortest Grid Path
Given a 2D grid where 0 represents an open cell and 1 represents an obstacle, find any shortest path from a start coordinate to a target coordinate.
Movement rules:
- You can move up, down, left, or right (four directions)
- Each move has unit cost
- You cannot move through obstacles (cells with value
1) - You cannot move outside the grid boundaries
Input coordinates:
start:[row, col]representing the starting positiontarget:[row, col]representing the target position
Return value:
- If a path exists: return one shortest path as a list of
[row, col]coordinates from start to target (both inclusive) - If no path exists: return an empty list
[] - If start or target is out of bounds: return
[] - If start or target is on an obstacle: return
[] - If start equals target and the cell is valid: return
[[start_row, start_col]]
When exploring neighbors during pathfinding, check them in this order: up (-1, 0), down (1, 0), left (0, -1), right (0, 1).
Function Signature
Your function receives six parameters:
words: list of stringsmax_width: positive integers: string containing only'(',')', and'*'grid: 2D list of integers (each cell is0or1)start: list of two integers[row, col]target: list of two integers[row, col]
Return a dictionary with exactly three keys:
"justified_lines": list of strings (Part 1 answer)"valid_parentheses": boolean (Part 2 answer)"shortest_path": list of[row, col]pairs (Part 3 answer)
Constraints
0 ≤ len(words) ≤ 3001 ≤ len(word) ≤ max_width ≤ 100for each word1 ≤ max_width ≤ 1000 ≤ len(s) ≤ 10000 ≤ len(grid) ≤ 1000 ≤ len(grid[0]) ≤ 100(if grid is non-empty)
Examples
Example 1
Input: solve_algorithm_trio(['This', 'is', 'an', 'example', 'of', 'text', 'justification.'], 16, '(*)', [[0, 0, 0], [1, 0, 0], [0, 0, 0]], [0, 0], [2, 2])
Output: {'justified_lines': ['This is an', 'example of text', 'justification. '], 'valid_parentheses': True, 'shortest_path': [[0, 0], [0, 1], [1, 1], [2, 1], [2, 2]]}
Example 2
Input: solve_algorithm_trio(['What', 'must', 'be', 'acknowledgment', 'shall', 'be'], 16, '((*)', [[0, 1], [0, 0]], [0, 0], [1, 1])
Output: {'justified_lines': ['What must be', 'acknowledgment ', 'shall be '], 'valid_parentheses': True, 'shortest_path': [[0, 0], [1, 0], [1, 1]]}
Hints
Hint 1
For text justification, track the cumulative character count as you add words to a line. Remember that each word after the first requires at least one space before it.
Hint 2
For parenthesis validation, maintain a range of possible balance values rather than a single balance. Wildcards expand this range.
Hint 3
For grid pathfinding, BFS with unit costs guarantees the first time you reach a cell is via a shortest path. Store parent pointers to reconstruct the path afterward.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
This problem tests three distinct algorithmic skills: greedy text formatting, range-based state tracking, and graph traversal with reconstruction.
Part 1: Full-Width Text Justification
Approach: Pack words onto each line greedily. Starting from position i, keep adding words as long as they fit. A word at position j fits if the total character count plus required spaces does not exceed the width limit. The condition is letters + len(words[j]) + (j - i) <= max_width, where (j - i) accounts for the single space that must precede each word after the first one on the line.
Once a line's words are determined (from index i to j-1), apply the appropriate formatting rule. The last line in the output and any line containing just one word use left justification: join words with single spaces and pad the right side. All other lines distribute spaces evenly across the gaps. With g gaps and s total spaces, use divmod(s, g) to get a base spacing and remainder. Each gap gets the base number of spaces, and the first remainder gaps get one extra space.
Why it works: The greedy packing strategy matches the problem specification—each line accommodates as many words as possible. The divmod operation ensures uniform space distribution with leftmost gaps receiving any extras. Single-word lines have no gaps, so left justification is the only valid approach.
Complexity:
- Time: O(L), where L is the total output character count
- Space: O(L) for the output list
Part 2: Wildcard Parenthesis Validation
Approach: Track an interval [low, high] representing all possible balance counts (open minus close parentheses) achievable at each position. Process each character:
'(': increment both bounds (balance increases)')': decrement both bounds (balance decreases)'*': decrementlow(interpret as')') and incrementhigh(interpret as'(')
After processing each character, if high < 0, too many closing parentheses exist even with optimal wildcard choices—the string is invalid. Also clamp low to 0 since negative balances represent invalid prefixes. After scanning the entire string, the string is valid if and only if low == 0, meaning a zero balance is achievable.
Why it works: Since wildcards can also represent empty strings, the set of reachable balance values forms a continuous interval. The interval approach captures all possibilities. Clamping low to 0 discards only the impossible negative states. When high drops below 0, the interval becomes empty and no valid interpretation exists. A final low == 0 confirms at least one path reaches perfect balance without ever going negative.
Complexity:
- Time: O(n) for string length n
- Space: O(1)
Part 3: Shortest Grid Path with BFS
Approach: Validate inputs first—check that start and target are within bounds and on open cells (value 0). If validation fails, return an empty list. Use breadth-first search since all moves have unit cost. Maintain a parent dictionary that serves dual purposes: tracking visited cells and recording where each cell was discovered from. Explore neighbors in the fixed order: up, down, left, right. When the target is reached, backtrack through parent pointers from target to start, collecting coordinates, then reverse the list.
Why it works: BFS explores cells in non-decreasing distance order. The first time any cell is reached is via a shortest path. Parent pointers recorded during exploration create a valid shortest path. Marking cells as visited when enqueued (not dequeued) prevents redundant work.
Complexity:
- Time: O(R × C) where R and C are the grid dimensions
- Space: O(R × C) for the queue and parent map
from collections import deque
from typing import Dict, List
def solve_algorithm_trio(words: List[str], max_width: int, s: str, grid: List[List[int]], start: List[int], target: List[int]) -> Dict[str, object]:
# Part 1: Format text with full justification
lines = []
i = 0
while i < len(words):
j = i
letters = 0
while j < len(words) and letters + len(words[j]) + (j - i) <= max_width:
letters += len(words[j])
j += 1
count = j - i
if j == len(words) or count == 1:
line = ' '.join(words[i:j])
lines.append(line + ' ' * (max_width - len(line)))
else:
gaps = count - 1
spaces = max_width - letters
base, extra = divmod(spaces, gaps)
line = ''
for k in range(gaps):
line += words[i + k] + ' ' * (base + (1 if k < extra else 0))
line += words[j - 1]
lines.append(line)
i = j
# Part 2: Validate parentheses with wildcards
low = high = 0
valid = True
for ch in s:
if ch == '(':
low += 1
high += 1
elif ch == ')':
low -= 1
high -= 1
else:
low -= 1
high += 1
if high < 0:
valid = False
break
low = max(low, 0)
valid = valid and low == 0
# Part 3: Find shortest path using BFS
path = []
rows = len(grid)
cols = len(grid[0]) if rows else 0
rs, cs = start
rt, ct = target
in_bounds = lambda r, c: 0 <= r < rows and 0 <= c < cols
if (in_bounds(rs, cs) and in_bounds(rt, ct)
and grid[rs][cs] == 0 and grid[rt][ct] == 0):
queue = deque([(rs, cs)])
parent = {(rs, cs): None}
directions = ((-1, 0), (1, 0), (0, -1), (0, 1))
while queue:
r, c = queue.popleft()
if (r, c) == (rt, ct):
break
for dr, dc in directions:
nr, nc = r + dr, c + dc
if (in_bounds(nr, nc) and grid[nr][nc] == 0
and (nr, nc) not in parent):
parent[(nr, nc)] = (r, c)
queue.append((nr, nc))
if (rt, ct) in parent:
current = (rt, ct)
while current is not None:
path.append([current[0], current[1]])
current = parent[current]
path.reverse()
return {"justified_lines": lines, "valid_parentheses": valid, "shortest_path": path}