Problem overview
This project lesson builds a tiny grep. The method grep(lines: string[], pattern: string): string returns every line that contains pattern as a substring, in their original order, joined by newline characters. The match is case-sensitive, and when no line matches the result is the empty string.
With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"], the result is "error: foo\nanother error". Printed, it is two lines:
error: foo
another error
The pattern is always plain text. Characters such as . or * mean nothing special: they are searched for literally.
Approach: filter, then join
The idea has three parts: test each line, collect the ones that pass, and turn the collection into one string. A substring test is exactly what the string method includes does, and it treats its argument as plain text, which is what the lesson wants. The collected lines go into an array, and join("\n") produces the final text.
Returning one string with newlines between lines, and no newline after the last one, is the reason to collect into an array first. Building the string with += would leave a separator at the start or end that has to be removed. join puts the separator only between two items, so an empty array gives "" and a one-item array gives that item alone.
Step by step
- Create the result. Declare
resultwithlet, typedstring[], and start it as an empty array. No line has matched yet. - Loop by position. A
forloop withifrom 0 whilei < lines.lengthvisits each line aslines[i]. - Test the line. Inside the loop,
if (lines[i].includes(pattern))is true when the pattern appears anywhere in the line, not only at the start. - Keep the line. Inside the
if,result.push(lines[i])adds it to the end of the array. Lines that fail the test are simply skipped. - Join and return. After the loop,
result.join("\n")glues the kept lines together with a newline between each pair.
The solution in TypeScript
class Solution {
grep(lines: string[], pattern: string): string {
let result: string[] = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes(pattern)) {
result.push(lines[i]);
}
}
return result.join("\n");
}
}
Details that matter in TypeScript:
String.prototype.includesis case-sensitive and treats its argument literally."a.b"as the pattern finds the three charactersa,.,bin a row: for["a.b", "axb"]the result is just"a.b".- The type annotation
string[]onresultmatters because an empty array literal has no elements to infer a type from. Writing it makes the intent clear. pushchanges the array in place and returns the new length, which this code ignores. The variableresultitself is never reassigned.join("\n")uses"\n", a single newline character. The result of[].join("\n")is"", which is exactly the "no match" answer, so no special case is needed.
Complexity
Each of the m lines is searched once. A substring search costs at most the line length times the pattern length in the worst case, and in practice about the line length. The running time is therefore proportional to the total size of the lines. The result array can hold every line, so the extra space is up to the size of the input.
Edge cases and common mistakes
- Case.
grep(["Error"], "err")returns"", because"Error"has a capitalE. Ignoring case is a different feature. - Anywhere in the line. Using
startsWithwould reject"another error", which containserrin the middle. - Special characters. The method does not interpret the pattern, so no escaping is needed. Building a regular expression from the pattern here would turn
.into "any character". - Trailing newline. Joining with
joinleaves nothing after the last line. A hand-built string with+= line + "\n"would leave a stray newline at the end. - Empty input. An empty array, or no matching line, gives
"".
Testing
| lines | pattern | Result |
|---|---|---|
["error: foo", "warning", "another error", "ok"] | "err" | "error: foo\nanother error" |
["error: foo", "warning", "another error", "ok"] | "zzz" | "" |
["a.b", "axb"] | "." | "a.b" |
["Error"] | "err" | "" |
The next version builds on this one.
