Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two elements in the array.
DSA Go
func swap(arr []int, i, j int) {
temp := arr[i]
arr[i] = arr[[1]]
arr[j] = temp
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong index like 0 or len(arr) causes runtime errors.
Swapping arr[i] with itself does nothing.
✗ Incorrect
We swap arr[i] with arr[j], so the blank must be 'j'.
2fill in blank
mediumComplete the code to generate permutations by recursion.
DSA Go
func permute(arr []int, start int) {
if start == len(arr) {
fmt.Println(arr)
return
}
for i := start; i < len(arr); i++ {
swap(arr, start, [1])
permute(arr, start+1)
swap(arr, start, i)
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with start instead of i causes no change.
Using len(arr) as index causes out-of-range error.
✗ Incorrect
We swap arr[start] with arr[i] to generate permutations.
3fill in blank
hardFix the error in the base case condition to stop recursion correctly.
DSA Go
func permute(arr []int, start int) {
if start [1] len(arr) {
fmt.Println(arr)
return
}
for i := start; i < len(arr); i++ {
swap(arr, start, i)
permute(arr, start+1)
swap(arr, start, i)
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' causes the base case to never trigger.
Using '>' or '<=' causes incorrect stopping condition.
✗ Incorrect
The base case is when start equals length of array, meaning all positions fixed.
4fill in blank
hardFill both blanks to create a function that returns all permutations as a slice of slices.
DSA Go
func permuteAll(arr []int, start int, result *[][]int) {
if start == len(arr) {
temp := make([]int, len(arr))
copy(temp, arr)
*result = append(*result, temp)
return
}
for i := start; i [1] len(arr); i++ {
swap(arr, start, i)
permuteAll(arr, start+1, result)
swap(arr, start, [2])
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes index out of range error.
Swapping back with start instead of i breaks permutation correctness.
✗ Incorrect
The loop runs while i < len(arr), and swap back uses i to restore original order.
5fill in blank
hardFill all three blanks to create a map of permutations with their string keys.
DSA Go
func permuteMap(arr []int, start int, result map[string][]int) {
if start == len(arr) {
key := fmt.Sprint(arr)
result[[1]] = [2]
return
}
for i := start; i < len(arr); i++ {
swap(arr, start, i)
permuteMap(arr, start+1, result)
swap(arr, start, i)
}
}
// Usage:
// result := make(map[string][]int)
// permuteMap(arr, 0, result)
Attempts:
3 left
💡 Hint
Common Mistakes
Using arr directly as value causes all map entries to point to same slice.
Using arr[:] is a slice but still references original array.
✗ Incorrect
We use 'key' as map key, and a copy of arr as value to avoid mutation; key is used again as map key.
