String Pattern Replacement
Learn this problemProblem statement
You are given an input string s, a pattern string pattern, and a replacement string replacement.
Return a new string where every non-overlapping occurrence of pattern in s is replaced by replacement.
Process the string from left to right. Once a match is replaced, continue scanning after the matched substring in the original input.
If pattern does not appear in s, return s unchanged. You may not use a built-in replace-all function.
Clarifications / Interview Discussion
Before implementing, clarify these rules:
- What should happen if
patternis empty? - Are matches case-sensitive?
- Should overlapping matches be replaced? If not, which match wins?
- What should happen if
replacementis empty? - What if
replacementitself containspattern? - Should newly inserted text be scanned again, or only the original input?
- What should happen if
patternis longer thans?
For this problem, use these assumptions:
patternis non-empty.- Matching is case-sensitive.
- Only non-overlapping matches are replaced.
- The scan proceeds from left to right.
replacementmay be empty, in which case the matched pattern is deleted.- If
replacementcontainspattern, do not recursively replace inside newly inserted text.
Function Signature
function replacePattern(s: string, pattern: string, replacement: string): stringFunction
replacePattern(s: String, pattern: String, replacement: String) → StringExamples
Example 1
s = "abcabc"pattern = "ab"replacement = "x"return = "xcxc"Both occurrences of ab are replaced from left to right.
Example 2
s = "aaaa"pattern = "aa"replacement = "b"return = "bb"The two matches are adjacent and non-overlapping: indices 0-1 and 2-3.
Example 3
s = "aaaa"pattern = "aaa"replacement = "x"return = "xa"Replace the leftmost match first, then continue after the matched substring. The overlapping match starting at index 1 is not used.
Example 4
s = "abc"pattern = "d"replacement = "x"return = "abc"pattern does not appear in s, so the original string is returned unchanged.
Example 5
s = "abab"pattern = "ab"replacement = ""return = ""An empty replacement deletes each matched occurrence.
Constraints
0 <= s.length <= 1000001 <= pattern.length <= 1000000 <= replacement.length <= 100000s,pattern, andreplacementcontain printable ASCII characters.
More Google problems
- Deduplicate Logs: Keep FirstONSITE INTERVIEW · Seen Jul 2026
- Deduplicate Logs: Keep LatestONSITE INTERVIEW · Seen Jul 2026
- Find a Template Across Binary-Tree LeavesONSITE INTERVIEW · Seen Jul 2026
- Maximum Programmer-Problem MatchingONSITE INTERVIEW · Seen Jul 2026
- Minimum Direction ViolationsONSITE INTERVIEW · Seen Jul 2026
- Stream Latest Log VersionsONSITE INTERVIEW · Seen Jul 2026
- Stream Unique Logs in Timestamp OrderONSITE INTERVIEW · Seen Jul 2026
- Top-K IP Addresses from File RecordsONSITE INTERVIEW · Seen Jul 2026