Build the -i flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring, ignoring letter case. Return the matching lines joined by newline characters (\n).
Function signature:
grepCaseInsensitive(lines, pattern)
Example:
Input: pattern = "ERR" lines = ["Error: 1", "ok"] Output: "Error: 1" When printed: Error: 1
The matching is case-insensitive but the original line (preserving its original casing) is returned. If no lines match, return the empty string "". The lines contain only ASCII characters.
Compute
pattern.toLowerCase() once. For each line, run line.toLowerCase().includes(lowerPattern). If true, push the ORIGINAL line.
The full solution:
class Solution {
grepCaseInsensitive(lines, pattern) {
let result = [];
let lowerPattern = pattern.toLowerCase();
for (let i = 0; i < lines.length; i++) {
if (lines[i].toLowerCase().includes(lowerPattern)) {
result.push(lines[i]);
}
}
return result.join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
