#833

Find And Replace in String

Medium
ArrayHash TableStringSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a list to collect parts of the string that need to be replaced and then constructs the final string in one go. This avoids repeated string concatenation, which is inefficient.

⚙️

Algorithm

6 steps
  1. 1Step 1: Create a list 'result' to hold parts of the final string.
  2. 2Step 2: Initialize a variable 'lastIndex' to track the end of the last replacement.
  3. 3Step 3: Loop through each index in 'indices'.
  4. 4Step 4: For each index, check if 'sources[i]' matches the substring of 's' starting at 'indices[i]'.
  5. 5Step 5: If it matches, add the substring from 'lastIndex' to 'indices[i]' and the corresponding 'targets[i]' to 'result'. Update 'lastIndex' to the end of the current replacement.
  6. 6Step 6: After the loop, add the remaining part of 's' from 'lastIndex' to 'result'. Join the list into a final string and return it.
solution.py15 lines
1s = 'abcd'
2indices = [0, 2]
3sources = ['a', 'cd']
4targets = ['eee', 'ffff']
5
6result = []
7lastIndex = 0
8for i in range(len(indices)):
9    if s[indices[i]:indices[i]+len(sources[i])] == sources[i]:
10        result.append(s[lastIndex:indices[i]])
11        result.append(targets[i])
12        lastIndex = indices[i] + len(sources[i])
13result.append(s[lastIndex:])
14final_result = ''.join(result)
15print(final_result)

Complexity note: The time complexity is O(n) because we only traverse the string once, and the space complexity is O(n) due to the storage of the result.

  • 1Replacements should not overlap, allowing for simpler logic.
  • 2Using a list to build the result is more efficient than repeated string concatenation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.