Strong Password Checker II Problem
#2299
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2299.
A password is said to be strong if it satisfies all the following criteria:
- It has at least
8characters. - It contains at least one lowercase letter.
- It contains at least one uppercase letter.
- It contains at least one digit.
- It contains at least one special character. The special characters are the characters in the following string:
"!@#$%^&*()-+". - It does not contain
2of the same character in adjacent positions (i.e.,"aab"violates this condition, but"aba"does not).
Given a string password, return true if it is a strong password. Otherwise, return false.
Example 1:
Input: password = "IloveLe3tcode!"
Output: true
Explanation: The password meets all the requirements. Therefore, we return true.
Example 2:
Input: password = "Me+You--IsMyDream"
Output: false
Explanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.
Example 3:
Input: password = "1aB!"
Output: false
Explanation: The password does not meet the length requirement. Therefore, we return false.
Constraints:
1 <= password.length <= 100passwordconsists of letters, digits, and special characters:"!@#$%^&*()-+".
Solution
Approach: Simulation + Bitmask
Return false if the length is below 8. Then scan once: fail on two equal adjacent characters, and set one bit of a mask for each of the four character kinds (lowercase, uppercase, digit, other). The password is strong when all four bits are set, i.e. the mask is 15.
Complexity: O(n) time, O(1) space, where n is the password length.
class Solution:
def strongPasswordCheckerII(self, password: str) -> bool:
if len(password) < 8:
return False
mask = 0
for i, c in enumerate(password):
if i and c == password[i - 1]:
return False
if c.islower():
mask |= 1
elif c.isupper():
mask |= 2
elif c.isdigit():
mask |= 4
else:
mask |= 8
return mask == 15