All problems
0844MediumArrayHash TableStringSorting

Patching a Label in One Pass

Tracked in this browser only
Write code

Trains the technique from

LeetCode 833Find And Replace in String

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A label reads s. A batch of patches is described by three lists of the same length: patch i targets position indices[i] of the label, looks for the text sources[i] starting exactly there, and if it finds it, replaces that text with targets[i].

A patch whose sources[i] does not appear at that exact position is discarded. Every patch is judged against the original label, never against the result of another patch, and the targeted stretches of two patches never overlap.

Return the label after every surviving patch is applied.

Examples

Example 1

Input
s = "abcdef", indices = [0, 4], sources = ["ab", "ef"], targets = ["wx", "yz"]
Output
"wxcdyz"

Both patches find their text where they expect it, so "ab" at position 0 becomes "wx" and "ef" at position 4 becomes "yz", leaving "cd" untouched.

Example 2

Input
s = "abcdef", indices = [0, 4], sources = ["ab", "gg"], targets = ["wx", "yz"]
Output
"wxcdef"

Position 4 holds "ef", not "gg", so that patch is discarded and only the first one is applied.

Example 3

Input
s = "abab", indices = [0, 2], sources = ["ab", "ba"], targets = ["q", "r"]
Output
"qab"

Position 0 holds "ab" so it becomes "q". Position 2 holds "ab", not "ba", so that patch is discarded.

Constraints

  • 1 <= s.length <= 1000
  • 1 <= indices.length <= 100
  • indices.length == sources.length
  • indices.length == targets.length
  • 0 <= indices[i] <= 999
  • 1 <= sources[i].length <= 50
  • 1 <= targets[i].length <= 50
  • s consists of lowercase English letters only
  • sources[i] and targets[i] consist of lowercase English letters only
  • Every index is inside s, and the stretches two patches target never overlap

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def patch_label(s: str, indices: list[int], sources: list[str], targets: list[str]) -> str:
Java
public String patchLabel(String s, int[] indices, String[] sources, String[] targets)
September 7
Apply