Ctrl K

Patch Text at Positions

Medium
An editor receives a string text and a batch of patches. Patch i is described by a position positions[i] (0-based), an expected fragment expected[i] and a new fragment replacements[i]. A patch applies only if the original text really contains expected[i] starting at positions[i]. In that case the fragment is replaced with replacements[i]. If the fragment does not match (or does not fit in the string), the patch is skipped. All patches are applied at once: positions always refer to the original string, never to a partly edited one. The fragments of applicable patches are guaranteed not to overlap. Return the string after all patches.
Example 1
text="sunnyday", positions=[0, 5], expected=["sun", "day"], replacements=["fun", "night"] → 'funnynight'

Both patches apply: "sun" sits at position 0 and "day" at position 5. The result is "fun" + "ny" + "night".

Example 2
text="overflow", positions=[4, 0], expected=["flaw", "ov"], replacements=["x", "und"] → 'underflow'

Position 4 holds "flow", not "flaw", so the first patch is skipped. The second one matches: "ov" becomes "und".

Example 3
text="abc", positions=[2], expected=["cd"], replacements=["z"] → 'abc'
Constraints
  • 1 ≤ len(text) ≤ 1000
  • 1 ≤ len(positions) = len(expected) = len(replacements) ≤ 100
  • 0 ≤ positions[i] < len(text)
  • 1 ≤ len(expected[i]), len(replacements[i]) ≤ 50
  • text and expected[i] consist of lowercase English letters
  • replacements[i] consist of English letters and digits
  • Fragments of applicable patches do not overlap
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAnagram Buckets MediumA Subsequence of One Word Only MediumMost Searched Words MediumWord Grown Letter by Letter MediumMerge Contact Cards Medium
loading Python…
Input
text="sunnyday", positions=[0, 5], expected=["sun", "day"], replacements=["fun", "night"]
Expected
'funnynight'

Run checks the first 3 tests in your browser. Submit checks all 93 tests on the server, hidden ones included.