Strong Password Checker - Problem

A password is considered strong if all of the following conditions are met:

  • It has at least 6 characters and at most 20 characters.
  • It contains at least one lowercase letter, at least one uppercase letter, and at least one digit.
  • It does not contain three repeating characters in a row (i.e., "Baaabb0" is weak, but "Baaba0" is strong).

Given a string password, return the minimum number of steps required to make the password strong. If the password is already strong, return 0.

In one step, you can:

  • Insert one character to password
  • Delete one character from password
  • Replace one character of password with another character

Input & Output

Example 1 — Short Password
$ Input: password = "a"
Output: 5
💡 Note: Password is too short (1 < 6) and missing uppercase and digit. Need max(6-1, 3) = 5 insertions: "a" → "Aa1bcd"
Example 2 — Repeating Characters
$ Input: password = "aaa111"
Output: 2
💡 Note: Length is 6 (good), has lowercase and digits, missing uppercase. Has "aaa" and "111" repeating. Need max(1 missing type, 2 replacements) = 2 steps.
Example 3 — Already Strong
$ Input: password = "Aa1bcde"
Output: 0
💡 Note: Length 7 is valid, has all character types, no repeating sequences. Already strong.

Constraints

  • 1 ≤ password.length ≤ 50
  • password consists of letters, digits, dot '.' or exclamation mark '!'

Visualization

Tap to expand
Strong Password Checker INPUT "a" Password Length: 1 Requirements Check: X Length 6-20: FAIL (1 char) OK Lowercase: PASS X Uppercase: FAIL X Digit: FAIL OK No 3 repeating: PASS ALGORITHM STEPS 1 Count Missing Types Missing: uppercase, digit missing_types = 2 2 Calculate Length Needed Current: 1, Min: 6 chars_to_add = 5 3 Greedy Optimization Insertions can fix both length AND missing types 4 Compute Min Steps max(chars_to_add, missing) = max(5, 2) = 5 len < 6: return max(6-len, miss) len > 20: handle deletions else: fix repeats + missing FINAL RESULT Minimum Steps 5 Example Transformation: "a" --> "aB1xyz" 5 insertions needed: 1. Insert 'B' (uppercase) 2. Insert '1' (digit) 3. Insert 'x' (length) 4. Insert 'y' (length) 5. Insert 'z' (length) Key Insight: For passwords shorter than 6 characters, insertions are always optimal because each insertion can simultaneously increase length AND add a missing character type (uppercase/digit). The greedy approach: max(characters_needed_for_length, missing_character_types) gives minimum steps. For "a": max(6-1, 2) = max(5, 2) = 5 steps needed. TutorialsPoint - Strong Password Checker | Greedy Optimization
Asked in
Google 15 Facebook 12 Microsoft 8
89.2K Views
Medium Frequency
~35 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen