Problem overview
The method grep(lines, pattern) is a small version of the Unix grep command. It receives an array of strings and a search text, and returns every line that contains the text as a substring, joined into one string with newline characters ("\n"). The match is case-sensitive, and if nothing matches the result is the empty string.
With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"], the lines "error: foo" and "another error" contain err, so the result is "error: foo\nanother error". Printed, that is two lines of text.
The pattern is plain text, not a regular expression: characters such as . or * mean nothing special, so a search for a.b finds a literal a.b and nothing else.
Approach: filter, then join
Go through the lines in order, keep the ones that pass the test, and build the output from the kept lines. Collecting the survivors in an array and joining them at the end is cleaner than gluing strings together as you go, because join puts the separator only between items. There is no trailing newline to remove, and no matches means an empty array, which joins to the empty string, exactly what the task asks for.
The test itself is String.prototype.includes. "error: foo".includes("err") is true when the text appears anywhere in the string, not only at the start, and it compares exactly, so capitals matter.
Step by step
- Create
resultas an empty array withlet. It starts empty because nothing has matched before any line is checked. - Loop over the positions with
for (let i = 0; i < lines.length; i++), so thatlines[i]is the current line. - Test the line with
if (lines[i].includes(pattern)). - Push the line onto
resultinside theif. Only lines that passed the test get there. - Return
result.join("\n")after the loop.
The solution in JavaScript
class Solution {
grep(lines, pattern) {
let result = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes(pattern)) {
result.push(lines[i]);
}
}
return result.join("\n");
}
}
Details a learner might trip on:
includestreats its argument as plain text. That is why the lesson can promise that.and*are not special: the call["a.b", "axb"]searched for"a.b"returns only"a.b".- The comparison is case-sensitive:
"Error".includes("err")isfalse. join("\n")puts the separator between items only, so a single match gives that line with no newline after it, and an empty array gives"".- The string
"\n"is one newline character. If you print the result withconsole.log, it shows as separate lines.
Complexity
Each line is checked once, and a substring search costs time proportional to the line's length times the pattern's length in the worst case, so the whole run is bounded by the total text size times the pattern length. The result array holds up to all the lines, so the extra space is O(L) references for L lines.
Edge cases and common mistakes
- No match. The result is
"", notnulland not an array. - Case.
"Error"does not match"err"here. - Empty pattern.
includes("")is true for every string, so every line would be kept. - Returning the array instead of the joined string.
- Building the string with
+= line + "\n", which leaves a trailing newline that the expected output does not have.
Testing
| lines | pattern | result |
|---|---|---|
["error: foo", "warning", "another error", "ok"] | "err" | "error: foo\nanother error" |
["a.b", "axb"] | "a.b" | "a.b" |
["ok"] | "err" | "" |
["Error"] | "err" | "" |
