A password is strong when all three rules hold: its length is between 6 and 20 characters; it has at least one lowercase letter, one uppercase letter and one digit; and no character appears three times in a row ("xxx" anywhere makes it weak).
In one step you may insert a character, delete a character, or replace one character with another. Given password, return the fewest steps that make it strong. A password that is already strong needs 0 steps.
Example 1
Input: password = "aaabbbb11111111cdefgh!" Output: 5 Why: 2 deletes to reach 20, then 3 replaces break the runs
2 more examples and the constraints
Example 2
Input: password = "x9" Output: 4 Why: 4 inserts reach length 6; one can be uppercase
Example 3
Input: password = "Unbrute42" Output: 0 Why: it already meets every rule
Constraints
- 1 ≤ length of password ≤ 50
- password holds letters, digits, '.' and '!'
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Greedy, one delete at a timeO(n²)
- Buckets by length mod 3O(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50 characters | Verdict |
|---|---|---|---|
| Greedy, one delete at a time | O(n²) | Passes; easy to argue | |
| Buckets by length mod 3 | O(n) | Best; no loop over deletes |
n = the length of the password, at most 50.
Edge cases to test
- Very short. "b" needs 5 inserts; two of them supply the uppercase letter and the digit.
- Short with a run. "aaaB1" needs only 1 step: inserting into the run also reaches length 6.
- Long with no runs. A 21-character password with every kind needs exactly 1 delete.
- One long run. 50 copies of "z": 30 deletes leave a run of 20, which needs 6 replaces, and those also cover the 2 missing kinds: 36.
Common mistakes
- Adding missing kinds to the replaces instead of taking the larger of the two, which double counts.
- Deleting from runs in any order when the password is too long, instead of the runs with L % 3 = 0 first.
- Treating the short case like the others: under 6, inserts break runs too, so it is max(missing, 6 − n).
How to talk through it
- 1Clarify. Which characters can appear? Does one step change exactly one character? Is an empty password possible?
- 2Split by length. Under 6 inserts, 6 to 20 replaces, over 20 deletes first. Say why one edit can fix two rules.
- 3Explain the mod 3 rule. A run of L needs L / 3 replaces; deletes save one sooner when L % 3 is 0, then 1.
- 4Code the buckets. Count the two buckets in one scan, then spend the deletes in order.
- 5Test out loud. Run "x9", "aaaB1" and a 21-character password, and check 4, 1 and 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?