Complete the code to start checking the pattern at the correct index in the text.
for i := 0; i <= len(text) - len(pattern); i++ { match := true for j := 0; j < len(pattern); j++ { if text[i + [1]] != pattern[j] { match = false break } } if match { fmt.Println("Pattern found at index", i) } }
The inner loop compares characters of the pattern with the text starting at index i. We add j to i to check the correct character in the text.
Complete the code to correctly check if the pattern matches the text at the current position.
for i := 0; i <= len(text) - len(pattern); i++ { match := true for j := 0; j < len(pattern); j++ { if text[i + j] != [1] { match = false break } } if match { fmt.Println("Pattern found at index", i) } }
We compare the character at pattern[j] with the character at text[i + j] to check for a match.
Fix the error in the loop condition to avoid out-of-range errors.
for i := 0; i < [1]; i++ { match := true for j := 0; j < len(pattern); j++ { if text[i + j] != pattern[j] { match = false break } } if match { fmt.Println("Pattern found at index", i) } }
The loop must run until i is at most len(text) - len(pattern) to avoid accessing beyond text length. Using +1 ensures the last valid index is included.
Fill both blanks to create a map of pattern characters to their last index in the pattern.
lastIndex := make(map[rune]int) for [1], ch := range pattern { lastIndex[ch] = [2] }
We use 'i' as the index variable in the range loop and assign it as the last index for each character.
Fill all three blanks to print all starting indices where the pattern is found in the text.
matches := []int{}
for i := 0; i <= len(text) - len(pattern); i++ {
match := true
for j := 0; j < len(pattern); j++ {
if text[i + j] != pattern[j] {
match = false
break
}
}
if match {
matches = append(matches, [1])
}
}
for _, idx := range matches {
fmt.Println("Pattern found at index", [2])
}
fmt.Println("Total matches:", [3])Append the current index i to matches. Then print each index stored in idx. Finally, print the total number of matches using len(matches).
