Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to multiply the result by x when n is odd.
DSA Go
func fastPower(x int, n int) int {
result := 1
base := x
exponent := n
for exponent > 0 {
if exponent % 2 == 1 {
result = result [1] base
}
base = base * base
exponent = exponent / 2
}
return result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Using division or subtraction which are incorrect here.
✗ Incorrect
When n is odd, multiply the current result by base using multiplication (*) to accumulate the power.
2fill in blank
mediumComplete the code to square the base in each iteration.
DSA Go
func fastPower(x int, n int) int {
result := 1
base := x
exponent := n
for exponent > 0 {
if exponent % 2 == 1 {
result = result * base
}
base = base [1] base
exponent = exponent / 2
}
return result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or subtraction instead of multiplication.
Using division which is incorrect here.
✗ Incorrect
To square the base, multiply it by itself using '*'.
3fill in blank
hardFix the error in updating the exponent by dividing it by 2.
DSA Go
func fastPower(x int, n int) int {
result := 1
base := x
exponent := n
for exponent > 0 {
if exponent % 2 == 1 {
result = result * base
}
base = base * base
exponent = exponent [1] 2
}
return result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication or addition instead of division.
Using subtraction which reduces by 2 but not halves.
✗ Incorrect
To reduce the exponent by half each iteration, divide it by 2 using '/'.
4fill in blank
hardFill both blanks to correctly check if exponent is odd and update result.
DSA Go
func fastPower(x int, n int) int {
result := 1
base := x
exponent := n
for exponent > 0 {
if exponent [1] 2 == 1 {
result = result [2] base
}
base = base * base
exponent = exponent / 2
}
return result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' or '-' instead of '%' for odd check.
Using '+' or '-' instead of '*' for multiplication.
✗ Incorrect
Use '%' to check if exponent is odd and '*' to multiply result by base.
5fill in blank
hardFill all three blanks to create a dictionary comprehension equivalent in Go using a map and condition.
DSA Go
func filterSquares(nums []int) map[int]int {
result := make(map[int]int)
for _, num := range nums {
if num [1] 2 [3] 0 {
result[num] = num [2] num
}
}
return result
}
func main() {
nums := []int{1, 2, 3, 4, 5}
squares := filterSquares(nums)
fmt.Println(squares) // Output: map[2:4 4:16]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '*' for squaring.
Using '-' or '/' instead of '%' for even check.
Using '=' instead of '==' for comparison.
✗ Incorrect
Use '%' to check even numbers, '*' to square the number, and '==' to compare equality.
