Problem overview
The function grepInvert(lines []string, pattern string) string is the -v flag of Unix grep: it returns the lines that do not contain pattern, in their original order, joined by newline characters (\n). The match is case-sensitive.
With pattern = "err" and lines = ["error", "ok", "another error", "fine"], the first and third lines contain err, so they are dropped and the result is "ok\nfine". If every line contains the pattern, nothing is left and the result is "".
Approach
This is the first version's filter turned upside down. Version 1 kept a line when strings.Contains(line, pattern) was true. Here a line is kept when that call is false. Everything else, the empty result slice, the loop, the append and the final join, stays the same.
In Go, putting ! in front of a boolean expression negates it. So the single change to the code is !strings.Contains(line, pattern). That is the whole feature, which makes this a good example of how a small, well-chosen building block can be reused in the opposite direction.
Step by step
- Create the empty
resultslice for the lines to keep. - Loop over the lines with
for _, line := range lines. - Test for absence.
if !strings.Contains(line, pattern)is true exactly when the pattern does not appear in the line. - Keep the line.
result = append(result, line), storing the grown slice back inresult. - Join with newlines and return. Joining an empty slice gives
"", which is the required answer when every line contained the pattern.
The solution in Go
func grepInvert(lines []string, pattern string) string {
result := []string{}
for _, line := range lines {
if !strings.Contains(line, pattern) {
result = append(result, line)
}
}
return strings.Join(result, "\n")
}
A few notes on the code:
!is the logical NOT operator. Go has nonotkeyword. The operator applies to the call that follows it, so!strings.Contains(line, pattern)reads "the line does not contain the pattern".- The order is preserved. Lines are appended as the loop meets them, so the output follows the input's order.
- Tabs for indentation. Go's formatter indents with tabs, which is why this solution uses them. Indentation has no effect on how the code runs.
- The line is added as it is. Empty lines don't contain a non-empty pattern, so they are kept:
["a", "", "b"]with pattern"x"returns"a\n\nb", with an empty line in the middle.
Complexity
Time: O(n * m) in the worst case, where n is the total length of the lines and m the length of the pattern, since each line is searched once. Space: O(k), where k is the size of the output: the kept lines are stored in result and then copied into one joined string.
Edge cases and common mistakes
- Every line matches.
["error", "another error"]with"err"gives"". - Empty pattern. Every string contains the empty string, so every line is rejected:
["error", "ok"]with""gives"". - Empty list. Nothing is visited and the result is
"". - Case-sensitive test.
["Error", "ok"]with"err"returns"Error\nok":Errorstarts with a capital, so it doesn't contain the lowercaseerrand survives. - Forgetting the
!. Without it the function behaves like version 1 and returns exactly the lines it should drop. - Parentheses.
!binds to the nearest expression. In!strings.Contains(line, pattern)it applies to the call's result, as intended. If the test grows to something like!a && b, it applies toaonly, and parentheses are needed to negate the whole condition.
Testing
["error", "ok", "another error", "fine"]with"err"gives"ok\nfine".["error", "another error"]with"err"gives"".["Error", "ok"]with"err"gives"Error\nok".["a", "", "b"]with"x"gives"a\n\nb".
