Find And Replace in String - Problem
Imagine you're working with a smart text editor that needs to perform multiple find-and-replace operations simultaneously. You're given a string s and need to perform k replacement operations based on three parallel arrays:
indices[]- where to look for replacementssources[]- what substrings to findtargets[]- what to replace them with
The key challenge is that all replacements must happen simultaneously - they shouldn't affect each other's indexing. For each operation i:
- Check if
sources[i]occurs at indexindices[i]in the original string - If it matches exactly, replace it with
targets[i] - If it doesn't match, do nothing
Example: If s = "abcd", indices = [0, 2], sources = ["ab", "ec"], targets = ["eee", "ffff"], then only the first replacement happens ("ab" at index 0), resulting in "eeecd".
Input & Output
basic_replacement.py โ Python
$
Input:
s = "abcd", indices = [0, 2], sources = ["ab", "ec"], targets = ["eee", "ffff"]
โบ
Output:
"eeecd"
๐ก Note:
"ab" at index 0 matches and gets replaced with "eee". "ec" at index 2 doesn't match (we have "cd"), so no replacement occurs.
multiple_replacements.py โ Python
$
Input:
s = "vmokgggqzp", indices = [3, 5, 1], sources = ["kg", "ggq", "mo"], targets = ["s", "so", "bfr"]
โบ
Output:
"vbfrssozp"
๐ก Note:
All three replacements are valid: "mo" at index 1 โ "bfr", "kg" at index 3 โ "s", "ggq" at index 5 โ "so".
no_replacements.py โ Python
$
Input:
s = "abcd", indices = [0, 2], sources = ["xz", "gh"], targets = ["eee", "ffff"]
โบ
Output:
"abcd"
๐ก Note:
Neither "xz" at index 0 nor "gh" at index 2 match the original string, so no replacements occur.
Visualization
Tap to expand
Understanding the Visualization
1
Validate All Replacements
Check each source substring matches at specified index
2
Sort by Position
Arrange valid replacements by starting index to process in order
3
Build Result String
Use two pointers to construct result by applying replacements and copying unchanged parts
4
Handle Simultaneous Changes
Process replacements without affecting each other's indices
Key Takeaway
๐ฏ Key Insight: Process all replacements based on the original string indices by validating first, then applying systematically to avoid conflicts
Time & Space Complexity
Time Complexity
O(n + k*m + k log k)
O(n) to scan string, O(k*m) for k replacements with average length m, O(k log k) for sorting
โก Linearithmic
Space Complexity
O(n + k)
O(n) for result string, O(k) for storing valid replacements
โก Linearithmic Space
Constraints
- 1 โค s.length โค 1000
- k == indices.length == sources.length == targets.length
- 0 โค k โค 100
- 0 โค indices[i] < s.length
- 1 โค sources[i].length, targets[i].length โค 50
- s consists of only lowercase English letters
- sources[i] and targets[i] consist of only lowercase English letters
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code