Grep with context lines
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Snowflake's coding round and at Google, last asked Feb 2026. It tests arrays, intervals and strings.
Implement a simplified grep. You get a list of text lines, a search string target, and a non-negative integer k. Return every line that contains target, together with up to k lines before it and up to k lines after it.
def grep_with_context(lines: list[str], target: str, k: int) -> list[str]: ...
Rules:
- A line matches if
targetappears anywhere in it as a case-sensitive substring, including inside a longer word."log"matches"catalog"but not"LOG". - Context windows stop at the start and end of the input.
- Each line appears at most once in the result, even if it is in the context of several matches.
- The result keeps the original line order.
Constraints: 0 <= len(lines) <= 10^5, each line up to 10^3 characters, 0 <= k <= 10^5.
Example 1
lines = ["boot ok", "disk warn", "net ok", "cpu ok", "fan warn", "done"]
target = "warn", k = 1
output = ["boot ok", "disk warn", "net ok", "cpu ok", "fan warn", "done"]
The windows are lines 0-2 and 3-5. Together they cover every line, each once.
Example 2
lines = ["a", "bx", "c", "d", "e", "fx", "g"]
target = "x", k = 0
output = ["bx", "fx"]
Be ready for follow-ups: different before/after counts, a -- separator between groups, and input too large to hold in memory.
Clarifying questions
- Is an empty
targeta match on every line? - Should overlapping or touching windows simply merge into one run?
- Is the output just the lines, or also their line numbers?
What a strong answer covers
- Scans once, finds matches with the
insubstring test, and tracks the furthest line already emitted so each line appears once. - For each match, emits lines from
max(last_emitted + 1, i - k)tomin(i + k, len - 1), in order: O(total characters) and never O(matches * k). - Stops windows at the start and end of the input.
- Keeps matching case-sensitive and inside longer words (
logincatalog). - Tests both examples,
k = 0, overlapping windows,klarger than the input and no matches.
Follow-ups
- Different counts before and after (
-Band-A). - Print
--between groups that do not touch. - Input too large for memory: stream lines with a buffer of the last
k.
Where it's asked
- Snowflake · Coding · Last asked Feb 202660 min · Live coding; senior loops may agree a small storage component together, then build it
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.

