Problem overview
The method grepInvert takes a List<String> named lines and a search string pattern. It returns the lines that do not contain the pattern as a substring, in their original order, joined by newline characters. The match is case-sensitive. If every line contains the pattern, the result is the empty string "".
For pattern = "err" and lines = ["error", "ok", "another error", "fine"] the result is "ok\nfine". Printed, that is:
ok
fine
This is the -v flag of Unix grep: the same test as the plain substring search, with the answer reversed.
Approach: keep the lines where the test is false
The previous version kept a line when line.contains(pattern) was true. Here the structure of the method stays the same and only the condition flips: keep a line when that call is false. In Java, putting ! in front of a boolean expression negates it, so the whole change is one character in the if.
Everything else carries over. A list collects the lines to keep because their number is unknown in advance, a for-each loop visits the lines in order so the order is preserved, and String.join turns the list into a single string with newlines between the elements.
Step by step
- Create
result, an emptyArrayListheld in aList<String>variable, for the lines to keep. - Loop over the lines with a for-each loop that names each entry
line. - Test for absence with
if (!line.contains(pattern)). The!applies to the wholecontainscall, so the condition is true exactly when the pattern is nowhere in the line. - Keep the line with
result.add(line). Only a line without the pattern reaches this statement. - Join and return with
String.join("\n", result). If every line contained the pattern, nothing was added, and joining an empty list gives"", which is the required answer.
The solution in Java
class Solution {
public String grepInvert(List<String> lines, String pattern) {
List<String> result = new ArrayList<>();
for (String line : lines) {
if (!line.contains(pattern)) {
result.add(line);
}
}
return String.join("\n", result);
}
}
The Java details worth a closer look:
- The scope of
!.!line.contains(pattern)reads as "not (line contains pattern)". The method call happens first, and the!flips its boolean result. There is no need for extra parentheses here. - The same literal search.
containscompares plain characters and is case-sensitive. With["Error", "error"]and the pattern"error", the line"Error"does not contain it, so the result is"Error". - Original order. Lines are appended as the loop reaches them, so the kept lines appear in the order they had in the input.
- Imports. A standalone file needs
import java.util.*;forListandArrayList.
Complexity
Let n be the number of lines and m the total number of characters in them.
Time: O(m * p) in the worst case, with p as the pattern length: every line is scanned once by contains, and the join copies the kept characters once. For short patterns this is close to O(m).
Space: O(n + m). The list holds up to n references and the joined string holds up to about m characters.
Edge cases and common mistakes
- Every line matches.
["error", "another error"]with"err"gives"". - An empty list. With no lines, nothing is kept and the result is
"". - An empty pattern. Every string contains
"", so every line is rejected:["a", "b"]with""gives"". - Empty lines are kept. An empty line does not contain a non-empty pattern, so it survives.
["a", "", "b"]with"z"gives"a\n\nb", with a blank line in the middle. - Nothing to remove.
["a", "b"]with"z"returns"a\nb", all lines. - Forgetting the
!. The method then behaves like the plain search and returns the opposite set of lines. - Removing from the list while looping. A tempting alternative is to call
lines.removeinside the loop. That changes the caller's list, and removing from anArrayListduring a for-each loop usually ends in aConcurrentModificationException. Building a separate result list avoids both problems.
Testing
["error", "ok", "another error", "fine"]with"err"gives"ok\nfine".["error", "another error"]with"err"gives"".["Error", "error"]with"error"gives"Error".["a", "", "b"]with"z"gives"a\n\nb".["a", "b"]with""gives"".
