Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if a subset sums to target using backtracking.
DSA Python
def subset_sum(nums, target, index=0): if target == 0: return True if index == len(nums) or target < 0: return False # Include nums[index] if subset_sum(nums, target - nums[index], index + 1): return True # Exclude nums[index] return subset_sum(nums, target, [1])
Attempts:
3 left
💡 Hint
Common Mistakes
Not increasing the index causes infinite recursion.
Using target instead of index in recursive call.
✗ Incorrect
We move to the next index when excluding the current number to explore other subsets.
2fill in blank
mediumComplete the code to find the maximum sum of non-adjacent elements using greedy approach.
DSA Python
def max_non_adjacent_sum(nums): incl = 0 excl = 0 for num in nums: new_excl = max(incl, excl) incl = excl + num excl = [1] return max(incl, excl)
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning excl to num causes wrong sums.
Not updating excl leads to incorrect results.
✗ Incorrect
We update excl to the maximum of previous incl and excl to avoid adjacent picks.
3fill in blank
hardFix the error in the backtracking code to generate all permutations of a list.
DSA Python
def permute(nums, path, used, res): if len(path) == len(nums): res.append(path[:]) return for i in range(len(nums)): if used[i]: continue used[i] = True path.append(nums[i]) permute(nums, path, used, res) path.pop() [1] = False
Attempts:
3 left
💡 Hint
Common Mistakes
Not resetting used[i] causes missing permutations.
Resetting wrong variable leads to errors.
✗ Incorrect
We must reset used[i] to False after backtracking to allow reuse of that element.
4fill in blank
hardFill both blanks to complete the backtracking code that solves the N-Queens problem.
DSA Python
def is_safe(board, row, col, n): for i in range(row): if board[i] == col or abs(board[i] - col) == row - i: return False return True def solve_n_queens(n, board=[], row=0, solutions=[]): if row == n: solutions.append(board[:]) return for col in range(n): if is_safe(board, row, col, n): board.append([1]) solve_n_queens(n, board, [2], solutions) board.pop()
Attempts:
3 left
💡 Hint
Common Mistakes
Appending row instead of col causes wrong board state.
Not incrementing row leads to infinite recursion.
✗ Incorrect
We add the current column to board and move to the next row (row + 1) in recursion.
5fill in blank
hardFill all three blanks to complete the code that demonstrates greedy failure on coin change problem.
DSA Python
def min_coins(coins, amount): coins.sort(reverse=True) count = 0 for coin in coins: while amount [1] coin: amount [2]= coin count [3] 1 return count
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' instead of '>=' causes wrong loop condition.
Using '+=' instead of '-=' reduces amount incorrectly.
✗ Incorrect
We use '>=' to check if coin fits, '-=' to reduce amount, and '+=' to count coins.
