Solving Leetcode Interviews in Seconds with AI: Strong Password Checker II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2299" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
A password is said to be strong if it satisfies all the following criteria: It has at least 8 characters. 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 2 of 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 <= 100 password consists of letters, digits, and special characters: "!@#$%^&()-+".
Explanation
Here's a solution to the strong password problem:
- High-Level Approach: The solution employs a series of boolean flags to track whether the password meets each individual criterion (length, lowercase, uppercase, digit, special character, and no adjacent duplicates). It iterates through the password string once, updating these flags based on the characters encountered.
- Complexity: O(n) runtime, O(1) storage, where n is the length of the password.
Code
def strongPasswordCheckerII(password: str) -> bool:
"""
Checks if a password is strong based on the defined criteria.
Args:
password: The password string to check.
Returns:
True if the password is strong, False otherwise.
"""
if len(password) < 8:
return False
has_lower = False
has_upper = False
has_digit = False
has_special = False
special_chars = "!@#$%^&*()-+"
for i in range(len(password)):
char = password[i]
if 'a' <= char <= 'z':
has_lower = True
elif 'A' <= char <= 'Z':
has_upper = True
elif '0' <= char <= '9':
has_digit = True
elif char in special_chars:
has_special = True
if i > 0 and password[i] == password[i - 1]:
return False
return has_lower and has_upper and has_digit and has_special