Replace pattern in string
Filed under Amazon
Free read 2 of 3Iterate through the string and check for the pattern starting at each index.
The question
Given a string and a pattern, replace all continuous occurrences of the pattern with a single 'X'.
Constraints
- Pattern length >= 1
- String length up to 10^5
- Must handle overlapping or nested patterns if applicable
Examples
- Input
- s='abcabcabc', pattern='abc'
- Output
- 'X'
- Why
- Three 'abc' sequences are replaced by one 'X'.
Approach
Iterate through the string and check for the pattern starting at each index.
Maintain a boolean flag to track if we are currently inside a continuous pattern sequence.
Use a list/buffer to collect characters, appending 'X' only when a sequence transition occurs.
Tips
- What they are testing: Test with empty strings and patterns longer than the string.
- Common mistake: Using string concatenation in a loop, which leads to O(N^2) performance.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.