Practice
letterCombinations('23')?
from collections import deque
def letterCombinations(digits):
if not digits:
return []
digit_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
queue = deque([''])
for digit in digits:
letters = digit_map[digit]
for _ in range(len(queue)):
prev = queue.popleft()
for char in letters:
queue.append(prev + char)
return list(queue)
print(letterCombinations('23'))
Solution
Step 1: Trace queue after processing digit '2'
Initial queue: [''] Letters for '2': 'abc' After processing: ['a', 'b', 'c']Step 2: Trace queue after processing digit '3'
Letters for '3': 'def' For each prefix in ['a', 'b', 'c'], append each letter: 'a' + 'd','e','f' -> 'ad','ae','af' 'b' + 'd','e','f' -> 'bd','be','bf' 'c' + 'd','e','f' -> 'cd','ce','cf' Final queue: ['ad','ae','af','bd','be','bf','cd','ce','cf']Final Answer:
Option C -> Option CQuick Check:
Output matches expected letter combinations for '23' [OK]
- Mixing order of combinations
- Confusing concatenation order
n queens on an nxn chessboard so that no two queens threaten each other. Which algorithmic approach guarantees finding all valid solutions efficiently by exploring partial placements and pruning invalid ones early?Solution
Step 1: Understand problem constraints
The problem requires counting all valid queen placements with no conflicts, which demands exploring all possibilities.Step 2: Identify suitable algorithm
Backtracking systematically tries each column per row and abandons partial solutions that violate constraints, ensuring correctness and pruning search space.Final Answer:
Option A -> Option AQuick Check:
Backtracking explores all valid configurations efficiently [OK]
- Assuming greedy placement always works
- Believing DP without conflict checks suffices
Solution
Step 1: Understand the problem requirement
The problem asks for the lexicographically next greater permutation, which requires finding the next sequence just larger than the current one.Step 2: Identify the optimal approach
The approach scanning from the end to find a pivot where the sequence stops increasing, swapping with the smallest greater element on the right, then reversing the suffix guarantees the next permutation in O(n) time without generating all permutations.Final Answer:
Option A -> Option AQuick Check:
Brute force is correct but inefficient; DP and greedy do not guarantee correct next permutation [OK]
- Thinking brute force is optimal
- Using greedy from start fails on suffix order
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)):
# BUG: removing characters other than parentheses
next_str = curr[:i] + curr[i+1:]
if next_str not in visited:
visited.add(next_str)
queue.append(next_str)
return res
What is the bug in this code?Solution
Step 1: Identify character removal condition
The code removes characters at every index without checking if they are '(' or ')', which is incorrect.Step 2: Consequence of bug
Removing non-parenthesis characters leads to invalid strings and unnecessary BFS states, increasing complexity and possibly missing valid results.Final Answer:
Option D -> Option DQuick Check:
Only parentheses should be removed to prune search space [OK]
- Removing all characters
- Incorrect visited updates
- Misusing found flag
Solution
Step 1: Understand reuse implications
Allowing reuse of cells means cycles can occur, causing infinite recursion without additional safeguards.Step 2: Identify correct prevention method
Memoization keyed by (row, col, Trie node) prevents revisiting the same state repeatedly, breaking cycles and infinite loops.Step 3: Evaluate other options
Removing visited marking alone causes infinite loops; depth limit is arbitrary and may miss valid paths; resetting visited marking still forbids reuse within one path.Final Answer:
Option A -> Option AQuick Check:
Memoization ensures correctness with cell reuse allowed [OK]
- Removing visited marking without cycle detection causes infinite loops.
