call(back)
Algorithms & Data StructureseasySign in to star problems

Replace Without Built-ins

Given a string like "amaaba", replace every occurrence of a pattern such as "aa" with another string — without using built-in string methods (no replace, find/indexOf, split).

replace_all("amaaba", "aa", "x")   ->  "amxba"
replace_all("aaa",    "aa", "x")   ->  "xa"      (non-overlapping, left to right)

Matches are non-overlapping and found left to right, and an empty pattern leaves the string unchanged.

Hints

Hint 1

Outer pointer walks the text; at each position, an inner pointer checks the pattern character by character.

Hint 2

On a full match, emit the replacement and jump the pattern's length; otherwise emit one character and step once.

Asked at