Problem · String

String Pattern Replacement

Learn this problem
EasyGoogleNEW GRADONSITE INTERVIEW
See Google hiring insights

Problem 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 pattern is empty?
  • Are matches case-sensitive?
  • Should overlapping matches be replaced? If not, which match wins?
  • What should happen if replacement is empty?
  • What if replacement itself contains pattern?
  • Should newly inserted text be scanned again, or only the original input?
  • What should happen if pattern is longer than s?

For this problem, use these assumptions:

  • pattern is non-empty.
  • Matching is case-sensitive.
  • Only non-overlapping matches are replaced.
  • The scan proceeds from left to right.
  • replacement may be empty, in which case the matched pattern is deleted.
  • If replacement contains pattern, do not recursively replace inside newly inserted text.

Function Signature

function replacePattern(s: string, pattern: string, replacement: string): string

Function

replacePattern(s: String, pattern: String, replacement: String) → String

Examples

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 <= 100000
  • 1 <= pattern.length <= 100000
  • 0 <= replacement.length <= 100000
  • s, pattern, and replacement contain printable ASCII characters.

More Google problems

drafts saved locally
public String replacePattern(String s, String pattern, String replacement) {
  // write your code here
}
s"abcabc"
pattern"ab"
replacement"x"
expected"xcxc"
checking account