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:
def grepCaseInsensitive(self, lines: List[str], pattern: str) -> str:
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.
Lowercase BOTH the pattern and each line before comparing. Lowercase the pattern just once outside the loop. Don't lose the original line — append it (not the lowercased version) when you have a match.
The full solution:
class Solution:
def grepCaseInsensitive(self, lines, pattern):
result = []
lowerPattern = pattern.lower()
for line in lines:
if lowerPattern in line.lower():
result.append(line)
return "\n".join(result)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
