Problem 833

Abstract / Summary

Replace all occurrences of a substring with another in a string and return the modified string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0833.py

class Solution:
    def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
        k = len(indices)

        # sort indices, keep relationships to sources and targets
        ordered = []
        for i, n in enumerate(indices):
            ordered.append(( n, i ))
        ordered.sort(reverse = True) # reverse order to cope with "parallel" updates
        print(ordered)

        result = s
        for pos, i in ordered:
            if pos >= len(result):
                continue

            if s[pos:].startswith(sources[i]):
                prefix = result[:pos]
                suffix = result[pos + len(sources[i]):]
                result = prefix + targets[i] + suffix

        return result
22 lines | 774 bytes | submitted October 7, 2023 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 51% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sorting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The Solution class implements a single method, findReplaceString, which receives an original string s, a list of start positions indices, a list of substrings sources, and a list of replacement strings targets. For each entry, if the substring of s beginning at the given index matches the corresponding source string, that segment is replaced by the target string. The method returns the fully transformed string after all applicable replacements have been applied.

Key Steps

The method begins by determining how many replacement operations are described:

k = len(indices)

Next, it creates a collection that pairs each index with its original position in the input lists. This pairing preserves the relationship between an index and its associated source and target strings:

ordered = []
for i, n in enumerate(indices):
    ordered.append((n, i))

The collection is then sorted in descending order of the start positions:

ordered.sort(reverse=True)   # reverse order to cope with "parallel" updates

Sorting in reverse order is crucial because later replacements that occur at higher indices do not affect the character positions of earlier replacements. By processing from right to left, the algorithm avoids the need to recompute indices after each modification.

The core transformation loop iterates over the sorted pairs. For each candidate replacement, the algorithm first checks whether the start position lies within the current result string. If the position is beyond the end of the string, the iteration simply continues:

if pos >= len(result):
    continue

When the position is valid, the method verifies that the substring of the original string s beginning at pos actually starts with the expected source string. This check ensures that only exact matches trigger a replacement:

if s[pos:].startswith(sources[i]):

If the match succeeds, the algorithm builds a new string by concatenating three parts: the prefix before the replacement, the target string, and the suffix after the replaced segment. Slicing is used to extract the prefix and suffix efficiently:

prefix = result[:pos]
suffix = result[pos + len(sources[i]):]
result = prefix + targets[i] + suffix

Finally, after all entries have been processed, the method returns the assembled result:

return result

Edge Cases Handled

The implementation explicitly guards against attempts to replace text starting beyond the current length of the string. By checking pos >= len(result), it skips any out-of-range indices without raising an error.

It also handles the situation where the source string does not match the characters at the specified index. The startswith test ensures that only exact matches lead to a substitution, leaving the original text untouched when the source differs.

Because the replacements are applied in descending order of their start positions, overlapping or adjacent replacement intervals are processed without interfering with each other. A replacement that occurs later in the string does not shift the indices of earlier replacements, thereby preserving the intended mapping even when the source and target strings have different lengths.

Performance Optimizations

Sorting the index-source-target triples in reverse order eliminates the need for index adjustments after each modification. This design choice reduces the overhead that would otherwise be required to recompute positions for subsequent replacements.

The use of Python’s built-in startswith method provides a fast, C-level check for prefix equality, avoiding manual character-by-character comparison.

String reconstruction relies on slicing (result[:pos] and result[pos + len(sources[i]):]) and concatenation of three short strings. While Python strings are immutable, this approach creates only one new string per successful replacement, minimizing the number of intermediate objects.

Overall, the algorithm processes each replacement exactly once, and the dominant cost comes from the initial sort, which is performed efficiently by Python’s highly optimized Timsort implementation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long piece of paper with a sentence written on it. Sometimes you want to take out a specific word and swap it for a different one. This code is like a little robot helper that knows how to make those swaps safely.

First, the robot looks at all the spots where you want to change something. It sorts these spots from the end of the sentence back to the beginning. It does this because if you change something at the front of a sentence, the rest of the words shift around and that makes it hard to find the other spots. By starting at the very end, the robot makes sure the spots it needs to find stay exactly where they are supposed to be.

The robot then looks at each spot one by one. It checks to see if the word you want to replace is actually sitting there waiting for it. If the word matches, the robot carefully cuts out the old piece and puts the new piece right in that empty space. It keeps doing this until every change you wanted is finished. Finally, you get to see your brand new sentence put back together with all the new words in place.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.52 | σ = 1.62

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python Java C++ TS
WalkCCC Python Java C++
leetcode.ca Python Java C++ Go TS
LeetcodeHelp Python Java C++
Progiez Python Java C++
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
JoshCrozier JS
lkwq007 Python
martianoff Scala
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
JoshCrozier JavaScript
lkwq007 Python
martianoff Scala
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
29 links | 16 authors | 10 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

3 easy 4 medium 1 hard
9 solutions   October 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality