Problem overview
The method grep takes a List<String> named lines and a search string pattern. It returns every line that contains the pattern as a substring, in their original order, joined into one string with newline characters between them. The match is case-sensitive. If no line matches, the result is the empty string "".
For pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"] the result is "error: foo\nanother error". Printed, that is two lines:
error: foo
another error
Real grep treats the pattern as a regular expression. Here the pattern is plain text, so characters such as . and * mean nothing special.
Approach: filter, then join
The task has two separate parts. First, filter: go through the lines and keep those where line.contains(pattern) is true. Second, format: glue the kept lines into a single string. Collecting the survivors in a list first keeps the two parts apart, and the second part becomes one library call.
A list is the natural container for the survivors because the number of matches is unknown in advance. An array needs its size fixed up front, while an ArrayList grows with each add.
Step by step
- Create
result, aList<String>set tonew ArrayList<>(). The diamond<>lets the compiler infer the element type from the variable's declared type. - Loop over the lines with a for-each loop. It hands over each
String linedirectly, so there is no index to manage. - Test each line with
if (line.contains(pattern)).containsis true when the pattern appears anywhere in the line, at the start, in the middle or at the end, not only at the beginning. - Keep the match with
result.add(line). Only lines that passed the test reach this statement, and the lines keep their original order because the loop visits them in order. - Join and return with
String.join("\n", result). The first argument goes between every two elements, and nothing is added before the first or after the last. Whenresultis empty, joining nothing gives"", which is exactly what the task asks for when no line matches, so no special case is needed.
The solution in Java
class Solution {
public String grep(List<String> lines, String pattern) {
List<String> result = new ArrayList<>();
for (String line : lines) {
if (line.contains(pattern)) {
result.add(line);
}
}
return String.join("\n", result);
}
}
The Java details worth a closer look:
containsis a literal search.String.containstakes aCharSequenceand compares characters exactly as given. Withpattern = "a.b"and the lines["a.b", "axb"], only"a.b"is returned: the dot is an ordinary character. Methods such asmatchesorsplitwork differently, because they read their argument as a regular expression.- Case matters.
containsdistinguishesEfrome. For["Error", "error"]and the pattern"error"the result is just"error". String.joinaccepts a list. Besides varargs strings, it takes anyIterableofCharSequence, soresultgoes in as it is.- Imports.
ListandArrayListlive injava.util; a standalone file needsimport java.util.*;. - The newline.
"\n"is a single newline character. There is no trailing newline after the last line, becausejoinonly places the separator between elements.
Complexity
Let n be the number of lines and m the total number of characters in them.
Time: O(m * p) in the worst case, where p is the pattern length. Each contains call scans one line, and a naive search may compare up to p characters at each position. For short patterns this is close to O(m). Joining the result copies at most every character once more.
Space: O(n + m). The list holds up to n references to existing strings, and the joined result is a new string of up to about m characters.
Edge cases and common mistakes
- No match.
["a", "b"]with"z"gives"". The same happens for an empty list of lines. - An empty pattern. Every string contains
"", so every line is kept:["one", "two"]with""gives"one\ntwo". - A single match. The result has no newline in it:
["only"]with"on"gives"only". - Ambiguous empty results. A list holding one empty line, with an empty pattern, also joins to
"". The result string alone cannot tell "no lines" from "one empty line". - Using
==orstartsWith.line == patterncompares references, andstartsWithonly checks the beginning. Neither does what the task describes. - Adding a newline to each line and returning the concatenation. That leaves a trailing newline that the expected result does not have.
Testing
["error: foo", "warning", "another error", "ok"]with"err"gives"error: foo\nanother error".["a", "b"]with"z"gives"".["a.b", "axb"]with"a.b"gives"a.b".["Error", "error"]with"error"gives"error".["one", "two"]with""gives"one\ntwo".
