Microsoft OA Interview Question: Maximum Operations on a String

15 Views
No Comments

Given a string s of lowercase English characters, the following operation can be performed any number of times:

Choose three consecutive characters s[i], s[i+1], and s[i+2] where 1 <= i <= |s| - 2 (1-based indexing) such that s[i] = s[i+1] and s[i+1] != s[i+2]. Replace s[i+2] with s[i].

Find the maximum number of operations that can be applied to s.

Example

s = "accept"

The following operations are performed (bold indicates the changed character):

1. Start at i = 2, "cce". The new string s'="acccpt"2. Start at i = 3, s' = "acccct"
3. Start at i = 4, s'="accccc"

No other selections are available. The operation can be applied a maximum of 3 times.

Function Description

Complete the function getMaximumOperations in the editor with the following parameters:

  • string s: the string to transform

Returns

  • long int: the maximum number of times the operation can be applied

The key idea is to avoid simulating every mutation and instead track how identical-character runs can expand. Each valid operation turns a pattern like <code>xxY</code> into <code>xxx</code>, so the process only propagates a run of equal letters to the right. A clean solution scans the string from right to left, maintains counts of pending characters for each letter, and accumulates the number of operations contributed by each expandable position. This leads to an efficient linear-time approach suitable for large inputs.

END
 0