Payments app~12 min2s · 256 MBtarget O(n) time, O(n) spacestrings
A payments app keeps the text of each support chat, so that agents can read it. Customers sometimes paste a card number into the chat, and the number must not be stored in full.
The app treats any run of 12 or more digits in a row as a card number. It keeps the last four digits and hides the others. A chat log can hold up to 100,000 characters.
Write mask_card_numbers(text).
text holds the letters a to z, the digits 0 to 9 and the space character.*.text.Input: text = "paid 4111111111111111 for order 77 ref 123456789012 ok"
Output: "paid ************1111 for order 77 ref ********9012 ok"Two runs are card numbers: one with 16 digits and one with exactly 12.
Scan once, and take each whole run of digits at a time.
| Run starts at | Digits | Length | A card number? | Written |
|---|---|---|---|---|
| 5 | 4111111111111111 | 16 | yes | ************1111 |
| 32 | 77 | 2 | no | 77 |
| 39 | 123456789012 | 12 | yes | ********9012 |
The other characters are copied as they are.
Input: text = "a 123456789012 b 12345678901"
Output: "a ********9012 b 12345678901"The first run has exactly 12 digits and is masked. The second has 11 and is left alone.
Input: text = "no digits here"
Output: "no digits here"Nothing to mask.
1 ≤ text.length ≤ 100,000 (characters in the chat log)text uses only a to z, 0 to 9 and the space characterA text can be one run of 100,000 digits. Finding the whole run again for every digit costs about n × n = 10^10 steps. One scan that finds each run once costs about n steps.