Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Online Grep With Context
00:00
5 left

Online Grep With Context

HardPython

Problem

Verily Study Watch ingestion logs can be too large to load into memory. Implement an online grep-style function that scans an iterable of log lines, selects lines matching a regular expression, and returns surrounding context while merging overlapping match regions.

Formal Specification

Implement grep_context(lines, pattern, before, after), where lines is an iterable of strings, pattern is a valid Python regular expression, and before and after are nonnegative integers. Return a list of match blocks. Each block is a list of [line_number, line] pairs, using one-based line numbers. Include up to before preceding lines and up to after following lines for every matching line. A line must appear at most once in a block. Merge blocks whose context ranges overlap or touch.

The function must process lines in one forward pass. Do not convert the input iterable to a list or assume it supports random access. The implementation may buffer only the context needed to decide whether a later match extends the current block.

Constraints

  • 0 <= before, after <= 10^4
  • 0 <= number of input lines <= 10^7
  • Each line contains at most 10^4 characters
  • pattern is a valid Python regular expression
  • Matching uses re.search independently for each line

Function Signature

def grep_context(lines, pattern, before, after):
Interviewer

Your question is Online Grep With Context. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.