Practice
getPermutation, what is the returned value when calling getPermutation(3, 3)?Solution
Step 1: Trace factorial array computation
factorial = [1, 1, 2] for n=3.Step 2: Calculate indices and build result
k=3 -> k=2 zero-based. For i=2: idx=2//2=1, pick '2'. For i=1: k=2%2=0, idx=0//1=0, pick '1'. For i=0: k=0%1=0, idx=0//1=0, pick '3'. Result = '213'.Final Answer:
Option C -> Option CQuick Check:
Output matches expected k-th permutation '213' [OK]
- Off-by-one error in k adjustment
- Wrong index calculation in loop
- Not popping used numbers
from collections import deque
def is_valid(s: str) -> bool:
count = 0
for c in s:
if c == '(': count += 1
elif c == ')':
count -= 1
if count < 0:
return False
return count == 0
def remove_invalid_parentheses_bfs(s: str):
res = []
visited = set([s])
queue = deque([s])
found = False
while queue:
size = len(queue)
for _ in range(size):
curr = queue.popleft()
if is_valid(curr):
res.append(curr)
found = True
if found:
continue
for i in range(len(curr)):
if curr[i] not in ('(', ')'):
continue
next_str = curr[:i] + curr[i+1:]
if next_str not in visited:
visited.add(next_str)
queue.append(next_str)
return res
print(remove_invalid_parentheses_bfs("()())()"))
What is the output of this code?Solution
Step 1: Trace BFS levels for input "()())()"
Initial string is invalid. BFS removes one parenthesis at each position generating candidates. The first valid strings found are "()()()" and "(())()".Step 2: Confirm both valid strings are collected
Since BFS stops adding new states after finding valid strings at current level, both minimal removal results are returned.Final Answer:
Option B -> Option BQuick Check:
Both minimal valid strings are returned [OK]
- Returning only one valid string
- Returning original invalid string
- Missing one minimal valid string
def partition(s):
def is_palindrome(left, right):
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
def backtrack(start, path):
if start == len(s):
result.append(path) # Line X
return
for end in range(start, len(s)):
if is_palindrome(start, end):
path.append(s[start:end+1])
backtrack(end+1, path)
path.pop()
result = []
backtrack(0, [])
return result
Solution
Step 1: Identify how results are stored
Appendingpathdirectly stores a reference, so later modifications affect all stored results.Step 2: Correct approach
Useresult.append(path[:])to append a copy, preserving each partition snapshot.Final Answer:
Option B -> Option BQuick Check:
Shared references cause incorrect final partitions [OK]
- Forgetting to copy path before appending
- Incorrect palindrome check boundaries
- Forgetting to pop after recursion
getPermutation:Solution
Step 1: Check k adjustment
k must be decremented by 1 to convert to zero-based indexing before using factorial divisions.Step 2: Understand impact of missing k -= 1
Without this, idx calculation is off by one, leading to incorrect permutation output.Final Answer:
Option A -> Option AQuick Check:
Missing k -= 1 causes wrong indexing and wrong permutation [OK]
- Forgetting zero-based index adjustment
- Misusing pop vs remove
- Incorrect factorial initialization
Solution
Step 1: Understand reuse of parentheses
Allowing reuse means we can insert parentheses anywhere, greatly increasing state space and complexity.Step 2: Analyze BFS suitability
Standard BFS only removes characters; it does not handle insertions, so it cannot explore all states correctly.Step 3: Identify correct approach
Backtracking with memoization can explicitly explore insertions and removals, pruning invalid states to handle reuse properly.Final Answer:
Option A -> Option AQuick Check:
Backtracking with memoization handles insertions and pruning [OK]
- Assuming BFS handles insertions
- Using greedy for complex insertions
- Modifying BFS without pruning leads to explosion
