Bakery Glaze Relabeling
Track contiguous group counts after global label replacements
A bakery has a fixed row of pastries. The lowercase letter at position i in labels identifies the glaze currently assigned to that pastry.
A glaze group is a maximal nonempty contiguous stretch of pastries with the same current letter.
Each string in changes contains exactly two lowercase letters. A change "xy" simultaneously replaces every current occurrence of x with y. Pastries do not move. If x is absent, or if x and y are equal, the row remains unchanged.
Apply the changes in order. Return an integer array whose element at index j is the number of glaze groups immediately after applying changes[j].
All replacements act on the current row, including replacements made by earlier changes.
Examples
Example 1
Input: labels = "aabbaca", changes = ["ba","ac","cc"] Output: [3,1,1]
Replacing b with a joins the neighboring a stretches. The later replacement of a with c also joins the remaining differently labeled stretches. Replacing a label with itself leaves the grouping unchanged.
Example 2
Input: labels = "abab", changes = ["bc","ca","ba"] Output: [4,1,1]
The first change only renames the b pastries because c is initially absent. The next change makes every pastry use a. A change whose source is absent has no effect.
Example 3
Input: labels = "z", changes = [] Output: []
No changes are requested, so there are no post-change group counts to report.
Constraints
- 1 <= labels.length <= 100000
- 0 <= changes.length <= 100000
- labels contains only lowercase English letters.
- Each changes[j] contains exactly two lowercase English letters.
Let n be the row length, q the number of changes, and d the number of distinct initial labels. The reference solution takes O(n log(d + 1) + q) time and O(n + d) auxiliary space, excluding the returned array. It uses exact bucket identities, not probabilistic fingerprints.
Hints
Show hint 1Hint 1
A group's boundary disappears exactly when two neighboring positions with different current labels become equal. Keep the total number of groups instead of recounting the row.
Show hint 2Hint 2
Separate a label's public name from its bucket of positions. When two buckets merge, inspect the smaller one; when a label is merely renamed to an absent label, only its name mapping needs to change.
Follow-up questions
What an interviewer might ask once you have a working solution.
- How would you adapt the solution if labels were arbitrary signed integers rather than lowercase letters?
- Prove that, when the smaller bucket is always moved, each position changes buckets at most logarithmically many times.
Practice this with an AI interviewer
Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.
Start this problem