Using a stamp is free, so apply it at every matching occurrence. For a stamp of length , let its occurrence endpoints be , with adjacent gaps . Coverage and effort are
Also consider the no-stamp cost .
Each suffix automaton state represents substrings with the same occurrence endpoint set and lengths
Find an optimal length in this interval for each state.
If , choose . Otherwise, set . If , choose . In the remaining case, find the -th largest gap and choose
If are the count and sum of gaps smaller than the chosen length, evaluate coverage as .
Obtain endpoint sets by merging upward along the suffix-link tree. Always insert the smaller set into the larger one: each endpoint moves only times. Maintain endpoints in an ordered set. Inserting an endpoint removes the old gap between its neighbors and creates up to two new gaps. A segment tree storing gap counts and sums supports these updates, prefix statistics, and order-statistic queries in each.
The answer is the minimum over all state optima and . The total complexity is time and space.
Proof
All matching occurrences of a stamp agree wherever they overlap. The first occurrence covers positions, and every subsequent occurrence adds new positions, giving the formula for . Every substring belongs to one SAM state and length, so optimizing every state considers every useful stamp.
For a fixed endpoint set,
This difference is nondecreasing, making discretely convex. If , the difference is always nonpositive, so is optimal. If and , it is always positive, so is optimal. Otherwise, the difference is nonpositive through the -th largest gap and positive afterward. Clamping to therefore gives an optimum.