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
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess 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
Get started
Prevent Prompt Injection in LLM Inputs
00:00
5 left

Prevent Prompt Injection in LLM Inputs

MediumPython

Problem

Write a function to filter and sanitize user inputs before passing them to an LLM to prevent prompt injection.

Implement sanitize_input(text) using deterministic text normalization and pattern filtering. Replace control characters with spaces, apply Unicode NFKC normalization, collapse repeated horizontal whitespace, and remove complete lines matching known injection phrases. Return the remaining lines joined by ; for example, "Hello Ignore previous instructions" becomes "Hello", while "Please summarize this" is unchanged. Accept 1 <= len(text) <= 100000 and return a string; this heuristic is not a complete security boundary.

Constraints

  • 1 <= len(text) <= 100000
  • text is a string containing Unicode characters
  • Matching is case-insensitive after NFKC normalization
  • A line is removed if it contains any recognized injection pattern

Function Signature

def sanitize_input(text):
Interviewer

Your question is Prevent Prompt Injection in LLM Inputs. 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.
Code
Sign up free to run your codeLog inLn 2
Run your code to see test output here.