Leetcode Problem #2299
A password is considered strong if the following criteria are all met:
!@#$%^&*()-+
Given a string password
, return true
if it is strong, otherwise return false
.
Q: Can the password contain spaces? A: The problem statement does not mention spaces, so let’s assume the password doesn’t contain spaces.
Q: What should be done if one of the criteria is not met?
A: Return false
if any single criterion isn’t met.
To determine if a password is strong, we will perform the following checks:
We will iterate through the password and use boolean flags to validate each criterion. If any criterion fails, we return false
. If all criteria are satisfied, we return true
.
def strongPasswordCheckerII(password: str) -> bool:
# Minimum length requirement
if len(password) < 8:
return False
has_lower = has_upper = has_digit = has_special = False
special_characters = "!@#$%^&*()-+"
for i in range(len(password)):
char = password[i]
# Checks for types of characters
if char.islower():
has_lower = True
elif char.isupper():
has_upper = True
elif char.isdigit():
has_digit = True
elif char in special_characters:
has_special = True
# Check for consecutive repeating characters
if i > 0 and password[i] == password[i - 1]:
return False
# All criteria must be satisfied
return has_lower and has_upper and has_digit and has_special
The algorithm iterates through the password once, making it an O(n) solution where n is the length of the password. This is efficient given the problem constraints.
We have implemented a function strongPasswordCheckerII
that validates a password against specific criteria to determine its strength. The function checks for length, character variety, and absence of consecutive repeating characters to ascertain password validity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?