Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the index of the target element in the slice.
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
Using the loop index 'i' instead of the target value for comparison.
Comparing with the entire array instead of a single element.
✗ Incorrect
The code compares each element arr[i] with the target value to find a match.
2fill in blank
mediumComplete the code to return -1 if the target is not found after the loop.
DSA Go
func linearSearch(arr []int, target int) int {
for i := 0; i < len(arr); i++ {
if arr[i] == target {
return i
}
}
return [1]
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 0 which could be a valid index.
Returning the length of the array which is out of bounds.
✗ Incorrect
Returning -1 indicates the target was not found in the slice.
3fill in blank
hardFix the error in the loop condition to avoid out-of-range errors.
DSA Go
func linearSearch(arr []int, target int) int {
for i := 0; i <= [1]; i++ {
if arr[i] == target {
return i
}
}
return -1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= len(arr) causes index out of range error.
Using 'i' or 'target' as loop boundary is incorrect.
✗ Incorrect
The loop should run while i is less than the last valid index, which is len(arr) - 1.
4fill in blank
hardFill both blanks to create a linear search that returns true if target is found, false otherwise.
DSA Go
func contains(arr []int, target int) bool {
for [1] := 0; [1] < len(arr); [1]++ {
if arr[[1]] == [2] {
return true
}
}
return false
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'j' instead of 'i' inconsistently.
Comparing with 'len(arr)' instead of 'target'.
✗ Incorrect
The loop variable 'i' is used to check each element against 'target'.
5fill in blank
hardFill in the blanks to create a linear search that returns the index of the first occurrence of target or -1 if not found.
DSA Go
func findIndex(arr []int, [1] int) int { for [2] := 0; [2] < len(arr); [2]++ { if arr[[2]] == [1] { return [2] } } return -1 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Returning the wrong variable as index.
✗ Incorrect
The function parameter is 'target', the loop variable is 'i', and the index returned is 'i'.