Problem overview
This is the -v flag of grep. The function grepInvert takes lines, a vector<string>, and a pattern, and returns the lines that do not contain the pattern as a substring. The test is case-sensitive. The remaining lines keep their original order and come back joined by newline characters. 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": the first and third lines contain err, so they are dropped.
Approach: flip the test
Version 1 of this tool kept the lines where find found the pattern. Here the loop is the same and only the condition changes: keep a line when lines[i].find(pattern) equals string::npos, which is the value find returns when the pattern is absent.
Everything else stays as before. A first flag decides whether a newline goes in front of a kept line, so newlines appear only between lines, never before the first or after the last.
Think of the two versions as one function with a switch on the test. Which lines are kept depends only on the condition; how they are joined does not. That is why a tool like this one can grow flags without rewriting its loop.
The empty pattern shows the idea clearly. Every line contains the empty string, so version 1 returns all lines and this version returns none. The two results always split the input into two complementary sets, and every line goes to exactly one of them.
The same condition can be written as !(lines[i].find(pattern) != string::npos). That reads as "not contains" and gives identical results, but the direct comparison with == is shorter and easier to read. Whichever form you choose, make sure the negation applies to the whole test and not to the position that find returns: !lines[i].find(pattern) is true only when the match is at position 0, which is a different question altogether.
Because the loop never changes, the function also stays correct for lines of any content, including empty lines: an empty line contains no pattern except the empty one, so it is kept for every non-empty pattern.
Step by step
- Create an empty
stringnamedresultfor the lines that are kept. - Create
bool first = true, meaning no line has been added yet. - Loop over the lines by position with
ifrom 0 whilei < lines.size(). - Keep the line only if the pattern is missing:
lines[i].find(pattern) == string::npos. - Add the separator with
if (!first) result += "\n";. - Append
lines[i]toresult. Only lines without the pattern get this far. - Set
firsttofalse. - Return
resultafter the loop. If every line had the pattern, nothing was added, andresultis still empty.
The solution in C++
class Solution {
public:
string grepInvert(vector<string> lines, string pattern) {
string result;
bool first = true;
for (int i = 0; i < lines.size(); i++) {
if (lines[i].find(pattern) == string::npos) {
if (!first) result += "\n";
result += lines[i];
first = false;
}
}
return result;
}
};
The C++ details worth a closer look:
==againstnposmeans "not found".findreturnsstring::nposonly when there is no match anywhere in the line. Any real position, including 0, means the pattern is present and the line must be dropped.- The condition is the whole change. Going from
!=to==turns "lines that match" into "lines that don't", and the rest of the function works for both. - The separator logic doesn't depend on the test. The flag records that a line was added, whatever the test was, so no newline appears before the first kept line.
- Lines are copied unchanged. The function doesn't trim or alter them; a kept line appears in the result exactly as it was in the input.
Complexity
Time. Each line is searched once. With a pattern of length m, searching a line of length n may take up to about n * m comparisons in the worst case, and appending the kept lines costs time proportional to their total length.
Space: O(total length). The result may hold copies of nearly every line, and the by-value parameters copy the input.
Edge cases and common mistakes
- Every line matches.
["error", "another error"]with"err"gives"". - Case matters.
["Error", "ok"]with"err"gives"Error\nok"."Error"has a capital E, so it does not containerrand is kept. - Empty pattern.
["a", "b"]with""gives"", because every line contains the empty string and all lines are dropped. - Testing for a position of 0. Writing a condition such as
find(pattern) < 0doesn't work: the result is unsigned and never negative. Compare withstring::npos. - Keeping the matching lines. Leaving
!=in place from version 1 returns the opposite set. - A stray newline. A newline written after every kept line leaves a trailing one that the expected result doesn't have.
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""gives"".
