Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to perform a linear search that returns the index of target or -1 if not found.
DSA Go
func linearSearch(arr []int, target int) int {
for i := 0; i < len(arr); i++ {
if arr[i] == [1] {
return i
}
}
return -1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing arr[i] with i instead of target
Using len(arr) instead of target in comparison
✗ Incorrect
The code compares each element arr[i] with the target value to find a match.
2fill in blank
mediumComplete the code to perform a binary search on a sorted array to find the target index or -1 if not found.
DSA Go
func binarySearch(arr []int, target int) int {
low, high := 0, len(arr)-1
for low <= high {
mid := (low + high) / 2
if arr[mid] == [1] {
return mid
} else if arr[mid] < target {
low = mid + 1
} else {
high = mid - 1
}
}
return -1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing arr[mid] with mid instead of target
Using low or high instead of target in comparison
✗ Incorrect
The binary search compares the middle element arr[mid] with the target to decide the search direction.
3fill in blank
hardFix the error in the binary search code: replace the incorrect operator to correctly update the high index.
DSA Go
if arr[mid] > target { [1] = mid - 1 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Updating low instead of high
Assigning mid or target instead of high
✗ Incorrect
When arr[mid] is greater than target, we reduce the high index to mid - 1 to search the left half.
4fill in blank
hardFill both blanks to create a loop that runs while low is less than or equal to high and calculates mid correctly.
DSA Go
for [1] <= [2] { mid := (low + high) / 2 // search logic }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using mid or target in the loop condition
Reversing low and high in the condition
✗ Incorrect
The loop continues while low is less than or equal to high to cover all elements in the search range.
5fill in blank
hardFill all three blanks to create a map comprehension that stores word lengths for words longer than 3 characters.
DSA Go
lengths := map[string]int{}
for _, word := range words {
if len(word) [1] 3 {
lengths[[2]] = [3]
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than operator instead of greater than
Using len(word) as key or word as value
✗ Incorrect
We check if the word length is greater than 3, then store the word as key and its length as value.