Practice
Solution
Step 1: Understand the problem requires all permutations
Generating all permutations means enumerating every possible ordering of the input elements without duplicates.Step 2: Identify the approach that systematically explores all orderings
Backtracking with a used array or in-place swapping explores all permutations by recursively building sequences or swapping elements, ensuring no duplicates and covering all possibilities.Final Answer:
Option A -> Option AQuick Check:
Backtracking is the standard method for generating all permutations [OK]
- Thinking greedy or sorting can generate all permutations without duplicates
"25525511135"?
from typing import List
def restore_ip_addresses(s: str) -> List[str]:
res = []
stack = [(0, [])] # (start index, path)
while stack:
start, path = stack.pop()
if len(path) == 4:
if start == len(s):
res.append(".".join(path))
continue
remaining_segments = 4 - len(path)
remaining_chars = len(s) - start
if remaining_chars < remaining_segments or remaining_chars > 3 * remaining_segments:
continue
for length in range(1, 4):
if start + length > len(s):
break
segment = s[start:start+length]
if (segment.startswith('0') and len(segment) > 1) or (length == 3 and int(segment) > 255):
continue
stack.append((start + length, path + [segment]))
return res
print(restore_ip_addresses("25525511135"))
Solution
Step 1: Trace initial stack and first expansions
Start with (0, []). Segments like '255', '25', '2' are pushed. Valid segments are checked for leading zeros and range.Step 2: Identify valid IP addresses found
Two valid IPs are found: "255.255.11.135" and "255.255.111.35". Both use all characters and have 4 segments.Final Answer:
Option C -> Option CQuick Check:
Both valid IPs appear in the result list [OK]
- Confusing order of results
- Missing one valid IP due to pruning
Solution
Step 1: Identify number of valid sequences
The number of valid parentheses sequences is the nth Catalan number, approximately 4^n / (n^{3/2}).Step 2: Analyze backtracking time
Backtracking generates all valid sequences, so time is proportional to number of sequences times sequence length, which is O(4^n / n^{3/2} * n) = O(4^n / n^{1/2}).Final Answer:
Option D -> Option DQuick Check:
Matches known Catalan number growth for valid parentheses [OK]
- Confusing brute force with backtracking complexity
- Assuming factorial complexity
def restore_ip_addresses(s: str) -> List[str]:
res = []
stack = [(0, [])]
while stack:
start, path = stack.pop()
if len(path) == 4:
if start == len(s):
res.append(".".join(path))
continue
remaining_segments = 4 - len(path)
remaining_chars = len(s) - start
if remaining_chars < remaining_segments or remaining_chars > 3 * remaining_segments:
continue
for length in range(1, 4):
if start + length > len(s):
break
segment = s[start:start+length]
# Bug: Missing check for leading zeros
if length == 3 and int(segment) > 255:
continue
stack.append((start + length, path + [segment]))
return res
Solution
Step 1: Identify missing validation
The code lacks a check to reject segments with leading zeros like '00' or '01', which are invalid.Step 2: Confirm other checks are correct
Check for segment > 255 and pruning are present and correct; appending to stack is correct.Final Answer:
Option A -> Option AQuick Check:
Missing leading zero check allows invalid IP segments [OK]
- Forgetting leading zero validation
- Misplacing pruning conditions
Solution
Step 1: Understand digit reuse impact
Allowing reuse means the index does not always increment; digits can be chosen repeatedly, risking infinite recursion.Step 2: Prevent infinite loops
Not incrementing index requires limiting recursion depth (e.g., max length n) to avoid infinite loops while exploring repeated digits.Step 3: Evaluate options
Modify backtracking to not increment index after choosing a digit, but limit recursion depth to n to prevent infinite loops correctly limits recursion depth while allowing reuse; others either cause infinite loops or incorrect pruning.Final Answer:
Option C -> Option CQuick Check:
Limiting recursion depth prevents infinite loops with reuse [OK]
- Forgetting to limit recursion depth causes infinite loops
