Problem overview
This is the -i flag of grep. The function grepCaseInsensitive takes lines, a vector<string>, and a pattern, and returns the lines that contain the pattern as a substring while ignoring letter case. The matching lines come back joined by newlines, unchanged, with their original capitals. If no line matches, the result is the empty string. The lines contain only ASCII characters.
With pattern = "ERR" and lines = ["Error: 1", "ok"] the result is "Error: 1". The pattern is in capitals and the line has Err, but they match once case is ignored, and the line is returned as it was written.
Approach: compare lowercase copies, keep the original
The previous version tested each line with find. To ignore case there is no need for a new search: make both sides the same case first. If the pattern and the line are both lowercase, ERR finds Error, and every other capitalization works as well.
Two details matter. First, the lowercase pattern is made once, before the loop, because it is the same for every line. Second, the lowercase line is only a temporary copy used for the test. What goes into the result is the original lines[i], since the statement asks for the lines with their original casing.
The starter code provides the helper toLower. It takes a string by value, which means it receives its own copy, replaces every character with its lowercase form using tolower, and returns the copy. The caller's string is never changed.
Step by step
- Create an empty
stringnamedresultfor the matching lines. - Create
bool first = true, which remembers that no line has been added yet. - Create
lowerPatternwithtoLower(pattern). Doing it before the loop converts the pattern once, not once per line. - Loop over the lines by position with
ifrom 0 whilei < lines.size(). - Test the lowercase line:
toLower(lines[i]).find(lowerPattern) != string::npos. Both sides are lowercase, andfindgivesstring::nposwhen there is no match. - Add the separator with
if (!first) result += "\n";, so the newline only goes between lines. - Append the original
lines[i]toresult, not the lowercase copy. - Set
firsttofalse. - Return
resultafter the loop. It is empty when nothing matched.
The solution in C++
class Solution {
public:
string toLower(string s) {
for (int i = 0; i < s.size(); i++) {
s[i] = tolower(s[i]);
}
return s;
}
string grepCaseInsensitive(vector<string> lines, string pattern) {
string result;
bool first = true;
string lowerPattern = toLower(pattern);
for (int i = 0; i < lines.size(); i++) {
if (toLower(lines[i]).find(lowerPattern) != string::npos) {
if (!first) result += "\n";
result += lines[i];
first = false;
}
}
return result;
}
};
The C++ details worth a closer look:
tolowerand its header.tolowercomes from<cctype>, already available in the lesson. It converts an uppercase letter to lowercase and leaves every other character alone, so digits, spaces and punctuation pass through.- Why ASCII only.
tolowerexpects a value that fits in anunsigned char(orEOF). A plaincharholding a byte of a non-ASCII character can be negative, and passing that is undefined behaviour. With ASCII text every value is in range, which is why the lesson restricts the input. - Passing by value is what protects the input. Inside
toLower,s[i] = tolower(s[i])changes the copy. The pattern and the lines in the caller stay untouched, and that is what lets the function return the original text. - A temporary in the condition.
toLower(lines[i])creates a new string that lives until the end of the test. It is not stored anywhere, andfindworks on it directly. - Member functions on a call result. You can call
.find(...)on the value thattoLowerreturns, just as you would on a variable.
Complexity
Time. Each line is lowercased in time proportional to its length, and then searched. With a pattern of length m, a plain substring search of a line of length n can take up to about n * m comparisons in the worst case. Lowercasing the pattern once adds only O(m).
Space: O(total length). The result holds copies of the matching lines, and the by-value parameters copy the input. The temporary lowercase line is as long as the longest line.
Edge cases and common mistakes
- Mixed case on both sides.
["Error: 1", "ok", "eRRor"]with"err"gives"Error: 1\neRRor". Both lines are returned exactly as written. - No match.
["ok", "fine"]with"ERR"gives"". - Returning the lowercase text. Appending
toLower(lines[i])to the result changes the output to lowercase. The test uses the copy; the result takes the original. - Lowercasing only one side. If only the line is lowercased, a pattern such as
"ERR"can never match, because the line has no capitals left. - Converting the pattern inside the loop. It works, but it repeats the same conversion for every line.
- Changing
linesin place. The helper takes its argument by value for this reason. Writing a version that editslines[i]would change the text that has to be returned in its original form.
Testing
["Error: 1", "ok"]with"ERR"gives"Error: 1".["Error: 1", "ok", "eRRor"]with"err"gives"Error: 1\neRRor".["WARNING: disk", "Warning", "ok"]with"warning"gives"WARNING: disk\nWarning".["ok", "fine"]with"ERR"gives"".
