Problem overview
The method grepCaseInsensitive takes a List<String> named lines and a search string pattern. It returns every line that contains the pattern as a substring, ignoring letter case, joined by newline characters. The lines come back exactly as they were given, capitals included. If nothing matches, the result is "". The lines contain only ASCII characters.
For pattern = "ERR" and lines = ["Error: 1", "ok"] the result is "Error: 1". The pattern is upper case and the line has Err, yet they match, and the line is returned with its original casing.
Approach: compare in one case, return the original
Substring search with contains is case-sensitive, so to ignore case, both sides of the comparison must be in the same case. Lowercasing both the pattern and the line makes ERR and Err into the same err.
The key point is what gets stored. The lowercase copy of a line exists only for the test. What goes into the result is the original line. That way the output keeps the capitalization of the input, which is what the real grep -i does.
The pattern is the same for every line, so it is lowercased once before the loop. The lines differ, so each one is lowercased as it is checked.
Step by step
- Create
result, an emptyArrayListdeclared as aList<String>, for the lines that match. - Lowercase the pattern once into
lowerPatternwithpattern.toLowerCase(). Doing it here, before the loop, avoids repeating the same work for every line. - Loop over the lines with a for-each loop, naming each entry
line. - Test the lowercase line.
line.toLowerCase().contains(lowerPattern)checks the substring with both sides in lower case. The line variable itself is not changed. - Add the original line with
result.add(line), capitals and all. - Join and return with
String.join("\n", result). An emptyresultjoins to"", the answer for no matches.
The solution in Java
class Solution {
public String grepCaseInsensitive(List<String> lines, String pattern) {
List<String> result = new ArrayList<>();
String lowerPattern = pattern.toLowerCase();
for (String line : lines) {
if (line.toLowerCase().contains(lowerPattern)) {
result.add(line);
}
}
return String.join("\n", result);
}
}
The Java details worth a closer look:
- Strings are immutable.
toLowerCase()does not change the string it is called on; it returns a new one. That is whylineis still the original afterwards and can be added toresultunchanged. Writingline.toLowerCase();as a statement on its own, without using the value, does nothing. - The locale.
toLowerCase()without arguments follows the default locale of the machine. For ASCII text this makes no difference in almost every locale, but Turkish rules, for example, lowercaseIto a dotlessı.toLowerCase(Locale.ROOT)gives the same answer everywhere; for the lesson's ASCII input both work. - An alternative.
equalsIgnoreCasecompares whole strings, not substrings, and there is nocontainsIgnoreCaseinString. Lowercasing both sides is the usual way to get substring search without regular expressions. - Imports. A standalone file needs
import java.util.*;forListandArrayList.
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, with p as the pattern length. Lowercasing a line costs its length, and then contains scans it. Lowercasing the pattern costs O(p) once.
Space: O(n + m). The list holds up to n references, the joined result can hold up to about m characters, and the lowercase copy of one line exists at a time while it is being tested.
Edge cases and common mistakes
- Several matches with different casing.
["Error: 1", "eRRor 2", "fine"]with"err"gives"Error: 1\neRRor 2", each line in its own original casing. - No match.
["abc"]with"xyz"gives"", and so does an empty list. - A pattern that spans a space.
["Hello World", "HELLO"]with"o w"gives"Hello World". Lowercasing treats spaces like any other character. - Adding the lowercase line.
result.add(line.toLowerCase())would match correctly but return"error: 1"instead of"Error: 1". - Lowercasing only one side. Calling
line.contains(lowerPattern)fails for["Error: 1"]because"Error: 1"does not contain"err"in that exact case. Both sides must be converted. - Lowercasing the pattern inside the loop. The result is correct, but the same conversion is repeated for every line.
Testing
["Error: 1", "ok"]with"ERR"gives"Error: 1".["Error: 1", "eRRor 2", "fine"]with"err"gives"Error: 1\neRRor 2".["abc"]with"xyz"gives"".["Hello World", "HELLO"]with"o w"gives"Hello World".[]with"a"gives"".
