Using greedy without proof
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
A password is considered strong if the below conditions are all met:
6 characters and at most 20 characters."Baaabb0" is weak, but "Baaba0" is strong).Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0.
In one step, you can:
password,password, orpassword with another character.Example 1:
Input: password = "a" Output: 5
Example 2:
Input: password = "aA1" Output: 3
Example 3:
Input: password = "1337C0d3" Output: 0
Constraints:
1 <= password.length <= 50password consists of letters, digits, dot '.' or exclamation mark '!'.Problem summary: A password is considered strong if the below conditions are all 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 password strong. if password is already strong, return 0. In one step, you can: Insert one character to password, Delete one character from password, or Replace one character of password with another character.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Greedy
"a"
"aA1"
"1337C0d3"
strong-password-checker-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #420: Strong Password Checker
class Solution {
public int strongPasswordChecker(String password) {
int types = countTypes(password);
int n = password.length();
if (n < 6) {
return Math.max(6 - n, 3 - types);
}
char[] chars = password.toCharArray();
if (n <= 20) {
int replace = 0;
int cnt = 0;
char prev = '~';
for (char curr : chars) {
if (curr == prev) {
++cnt;
} else {
replace += cnt / 3;
cnt = 1;
prev = curr;
}
}
replace += cnt / 3;
return Math.max(replace, 3 - types);
}
int replace = 0, remove = n - 20;
int remove2 = 0;
int cnt = 0;
char prev = '~';
for (char curr : chars) {
if (curr == prev) {
++cnt;
} else {
if (remove > 0 && cnt >= 3) {
if (cnt % 3 == 0) {
--remove;
--replace;
} else if (cnt % 3 == 1) {
++remove2;
}
}
replace += cnt / 3;
cnt = 1;
prev = curr;
}
}
if (remove > 0 && cnt >= 3) {
if (cnt % 3 == 0) {
--remove;
--replace;
} else if (cnt % 3 == 1) {
++remove2;
}
}
replace += cnt / 3;
int use2 = Math.min(Math.min(replace, remove2), remove / 2);
replace -= use2;
remove -= use2 * 2;
int use3 = Math.min(replace, remove / 3);
replace -= use3;
remove -= use3 * 3;
return (n - 20) + Math.max(replace, 3 - types);
}
private int countTypes(String s) {
int a = 0, b = 0, c = 0;
for (char ch : s.toCharArray()) {
if (Character.isLowerCase(ch)) {
a = 1;
} else if (Character.isUpperCase(ch)) {
b = 1;
} else if (Character.isDigit(ch)) {
c = 1;
}
}
return a + b + c;
}
}
// Accepted solution for LeetCode #420: Strong Password Checker
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #420: Strong Password Checker
// class Solution {
// public int strongPasswordChecker(String password) {
// int types = countTypes(password);
// int n = password.length();
// if (n < 6) {
// return Math.max(6 - n, 3 - types);
// }
// char[] chars = password.toCharArray();
// if (n <= 20) {
// int replace = 0;
// int cnt = 0;
// char prev = '~';
// for (char curr : chars) {
// if (curr == prev) {
// ++cnt;
// } else {
// replace += cnt / 3;
// cnt = 1;
// prev = curr;
// }
// }
// replace += cnt / 3;
// return Math.max(replace, 3 - types);
// }
// int replace = 0, remove = n - 20;
// int remove2 = 0;
// int cnt = 0;
// char prev = '~';
// for (char curr : chars) {
// if (curr == prev) {
// ++cnt;
// } else {
// if (remove > 0 && cnt >= 3) {
// if (cnt % 3 == 0) {
// --remove;
// --replace;
// } else if (cnt % 3 == 1) {
// ++remove2;
// }
// }
// replace += cnt / 3;
// cnt = 1;
// prev = curr;
// }
// }
// if (remove > 0 && cnt >= 3) {
// if (cnt % 3 == 0) {
// --remove;
// --replace;
// } else if (cnt % 3 == 1) {
// ++remove2;
// }
// }
// replace += cnt / 3;
//
// int use2 = Math.min(Math.min(replace, remove2), remove / 2);
// replace -= use2;
// remove -= use2 * 2;
//
// int use3 = Math.min(replace, remove / 3);
// replace -= use3;
// remove -= use3 * 3;
// return (n - 20) + Math.max(replace, 3 - types);
// }
//
// private int countTypes(String s) {
// int a = 0, b = 0, c = 0;
// for (char ch : s.toCharArray()) {
// if (Character.isLowerCase(ch)) {
// a = 1;
// } else if (Character.isUpperCase(ch)) {
// b = 1;
// } else if (Character.isDigit(ch)) {
// c = 1;
// }
// }
// return a + b + c;
// }
// }
# Accepted solution for LeetCode #420: Strong Password Checker
class Solution:
def strongPasswordChecker(self, password: str) -> int:
def countTypes(s):
a = b = c = 0
for ch in s:
if ch.islower():
a = 1
elif ch.isupper():
b = 1
elif ch.isdigit():
c = 1
return a + b + c
types = countTypes(password)
n = len(password)
if n < 6:
return max(6 - n, 3 - types)
if n <= 20:
replace = cnt = 0
prev = '~'
for curr in password:
if curr == prev:
cnt += 1
else:
replace += cnt // 3
cnt = 1
prev = curr
replace += cnt // 3
return max(replace, 3 - types)
replace = cnt = 0
remove, remove2 = n - 20, 0
prev = '~'
for curr in password:
if curr == prev:
cnt += 1
else:
if remove > 0 and cnt >= 3:
if cnt % 3 == 0:
remove -= 1
replace -= 1
elif cnt % 3 == 1:
remove2 += 1
replace += cnt // 3
cnt = 1
prev = curr
if remove > 0 and cnt >= 3:
if cnt % 3 == 0:
remove -= 1
replace -= 1
elif cnt % 3 == 1:
remove2 += 1
replace += cnt // 3
use2 = min(replace, remove2, remove // 2)
replace -= use2
remove -= use2 * 2
use3 = min(replace, remove // 3)
replace -= use3
remove -= use3 * 3
return n - 20 + max(replace, 3 - types)
// Accepted solution for LeetCode #420: Strong Password Checker
struct Solution;
impl Solution {
fn strong_password_checker(s: String) -> i32 {
let mut missing = 3;
let s: Vec<char> = s.chars().collect();
if s.iter().any(|c| c.is_lowercase()) {
missing -= 1;
}
if s.iter().any(|c| c.is_uppercase()) {
missing -= 1;
}
if s.iter().any(|c| c.is_digit(10)) {
missing -= 1;
}
let mut replace = 0;
let mut one = 0;
let mut two = 0;
let mut three = 0;
let mut i = 2;
while i < s.len() {
if s[i] == s[i - 1] && s[i] == s[i - 2] {
let mut length = 2;
while i < s.len() && s[i] == s[i - 1] {
length += 1;
i += 1;
}
replace += length / 3;
if length % 3 == 0 {
one += 1;
} else if length % 3 == 1 {
two += 1;
} else {
three += 1;
}
} else {
i += 1;
}
}
if s.len() < 6 {
return missing.max(6 - s.len()) as i32;
}
if s.len() <= 20 {
return missing.max(replace) as i32;
}
let delete = s.len() - 20;
let delete_one = one.min(delete);
let delete_one_left = delete - delete_one;
let delete_two = (two * 2).min(delete_one_left);
let delete_two_left = delete_one_left - delete_two;
let delete_three = ((one + two + three) * 3).min(delete_two_left);
replace -= delete_one + delete_two / 2 + delete_three / 3;
(delete + missing.max(replace)) as i32
}
}
#[test]
fn test() {
let s = "aaa111".to_string();
let res = 2;
assert_eq!(Solution::strong_password_checker(s), res);
let s = "ABABABABABABABABABAB1".to_string();
let res = 2;
assert_eq!(Solution::strong_password_checker(s), res);
let s = "1Abababcaaaabababababa".to_string();
let res = 2;
assert_eq!(Solution::strong_password_checker(s), res);
}
// Accepted solution for LeetCode #420: Strong Password Checker
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #420: Strong Password Checker
// class Solution {
// public int strongPasswordChecker(String password) {
// int types = countTypes(password);
// int n = password.length();
// if (n < 6) {
// return Math.max(6 - n, 3 - types);
// }
// char[] chars = password.toCharArray();
// if (n <= 20) {
// int replace = 0;
// int cnt = 0;
// char prev = '~';
// for (char curr : chars) {
// if (curr == prev) {
// ++cnt;
// } else {
// replace += cnt / 3;
// cnt = 1;
// prev = curr;
// }
// }
// replace += cnt / 3;
// return Math.max(replace, 3 - types);
// }
// int replace = 0, remove = n - 20;
// int remove2 = 0;
// int cnt = 0;
// char prev = '~';
// for (char curr : chars) {
// if (curr == prev) {
// ++cnt;
// } else {
// if (remove > 0 && cnt >= 3) {
// if (cnt % 3 == 0) {
// --remove;
// --replace;
// } else if (cnt % 3 == 1) {
// ++remove2;
// }
// }
// replace += cnt / 3;
// cnt = 1;
// prev = curr;
// }
// }
// if (remove > 0 && cnt >= 3) {
// if (cnt % 3 == 0) {
// --remove;
// --replace;
// } else if (cnt % 3 == 1) {
// ++remove2;
// }
// }
// replace += cnt / 3;
//
// int use2 = Math.min(Math.min(replace, remove2), remove / 2);
// replace -= use2;
// remove -= use2 * 2;
//
// int use3 = Math.min(replace, remove / 3);
// replace -= use3;
// remove -= use3 * 3;
// return (n - 20) + Math.max(replace, 3 - types);
// }
//
// private int countTypes(String s) {
// int a = 0, b = 0, c = 0;
// for (char ch : s.toCharArray()) {
// if (Character.isLowerCase(ch)) {
// a = 1;
// } else if (Character.isUpperCase(ch)) {
// b = 1;
// } else if (Character.isDigit(ch)) {
// c = 1;
// }
// }
// return a + b + c;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.