Minimum Operations to Reduce a Transaction Ledger
Problem statement
You are given a lowercase string transactionLedger. In one operation, choose an index whose character is c:
- If another
cexists to its left, remove the nearest such occurrence. - If another
cexists to its right, remove the nearest such occurrence.
The chosen character is not removed. After the removals, the remaining characters close up while preserving their relative order. Continue until the ledger cannot be reduced further.
Return the minimum number of operations needed to reduce the ledger as much as possible. An operation with no removable occurrence does not help and is never required.
Function
minProcessingSteps(transactionLedger: String) → intExamples
Example 1
transactionLedger = "baabacaa"return = 3- Choose the
bat index0. Remove the nextbat index3, obtainingbaaacaa. - Choose the
aat index2. Remove the nearest equal characters at indices1and3, obtainingbacaa. - Choose the
aat index3. Remove the equal characters at indices1and4, obtainingbca.
No character now has another equal occurrence. Three operations are necessary and sufficient.
Example 2
transactionLedger = "aaaa"return = 2First choose an interior a to remove two equal neighbors, leaving aa. A second operation removes one of those two characters. One operation cannot remove all three required occurrences.
Example 3
transactionLedger = "xyz"return = 0The string is already fully reduced because every character is distinct. No operation is needed.
Constraints
1 <= transactionLedger.length() <= 100000transactionLedgercontains only lowercase English letters.