Find And Replace in String
Real-world version: Patching a Label in One PassThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def patch_label(s: str, indices: list[int], sources: list[str], targets: list[str]) -> str:public String patchLabel(String s, int[] indices, String[] sources, String[] targets)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 13 test cases: 13 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Sort the PeopleReal-world version: Season Leaderboard From Two Parallel ListsEasy
- Find Resultant Array After Removing AnagramsReal-world version: Clearing Rearranged Labels Off the ShelfEasy
- Group AnagramsReal-world version: Bin Label FamiliesMedium
- Accounts MergeReal-world version: Merge Crew Badge RecordsMedium