Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Prevent Prompt Injection in LLM Inputs

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Prevent Prompt Injection in LLM Inputs. Start with the requirements on the right.

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.

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):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output