Problem overview
This first grep version filters lines. grep(lines: Array[String], pattern: String): String returns every line that contains pattern as a substring, in the original order, joined by newline characters (\n) into one string. 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 lines "error: foo" and "another error" contain err, so the result is "error: foo\nanother error". Printed, that is two lines.
The pattern is always plain text. Real grep reads its pattern as a regular expression by default, but here characters such as . and * mean nothing special and are searched for literally.
Approach
Go through the lines once, keep the ones that pass a test, and glue the kept lines together at the end. The test is the string method contains, which looks for the pattern anywhere in the line, not only at the start. Because contains takes the text literally, no escaping is needed for special characters: "a.c".contains("a.c") is true, while "abc".contains("a.c") is false.
The kept lines go into a growable collection. An Array has a fixed size, and the number of matches isn't known in advance, so the lesson uses a mutable ArrayBuffer. Scala's default collections are immutable, so the full name scala.collection.mutable.ArrayBuffer says explicitly that this one can grow.
Finally, mkString("\n") joins the buffer's items with a newline between each two. It puts the separator only between items, never after the last one, so the result has no trailing newline. For an empty buffer it returns the empty string, which is the result the statement asks for when nothing matches.
Step by step
- Create the buffer. A
valnamedresultholds an emptyArrayBuffer[String]. Avalis enough, since lines are added to the buffer and the buffer is never replaced. - Loop over the lines with
for (line <- lines). - Test each line with
line.contains(pattern)inside anif. - Keep the match. Inside the
if,result += lineappends the line to the buffer. - Join and return. After the loop,
result.mkString("\n")produces the answer.
The solution in Scala
class Solution {
def grep(lines: Array[String], pattern: String): String = {
val result = scala.collection.mutable.ArrayBuffer[String]()
for (line <- lines) {
if (line.contains(pattern)) {
result += line
}
}
return result.mkString("\n")
}
}
Details worth knowing:
ArrayBuffer[String]()creates an empty buffer without writingnew. The element type in the brackets is what lets+=accept only strings.result += linechanges the buffer in place. It works on avalbecause the reference stays the same while the contents change.containsis case-sensitive, so"Error".contains("err")is false.- An empty pattern is contained in every string, so
pattern = ""keeps all the lines.
Complexity
Each line is tested once, and a substring search costs time proportional to the line's length times the pattern's length in the worst case. With n lines the work is proportional to the total size of the input. The buffer can hold every line, so the extra space is O(n) references to lines that already exist, plus the joined result string.
Edge cases and common mistakes
- No matches. The buffer stays empty and
mkStringreturns"". No special case is needed. - Adding a newline after every line. That leaves a trailing newline. Let
mkStringplace the separators. - Treating the pattern as a regular expression. Searching with
containskeeps.and*literal, as the lesson requires. - Matching only at the start.
startsWithwould reject"another error"for the patternerr. - Case.
"ERR"finds nothing in"error: foo". Ignoring case is a separate feature.
Testing
| lines | pattern | Result |
|---|---|---|
Array("error: foo", "warning", "another error", "ok") | "err" | "error: foo\nanother error" |
Array("a.c", "abc", "a*") | "a.c" | "a.c" |
Array("a.c", "abc", "a*") | "a*" | "a*" |
Array("x", "y") | "z" | "" |
Array("x", "y") | "" | "x\ny" |
