โ† Amazon questions

Replace pattern in string

Filed under Amazon

Free read 2 of 3

Iterate 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

  1. Iterate through the string and check for the pattern starting at each index.

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.