Validate Password Against Multiple Rules
Otter.AiSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to efficiently iterate through a string while maintaining multiple state-based flags to satisfy diverse validation criteria.
Validate Password Strength
Given a string password, implement a function that returns True if the password meets all the following security requirements, and False otherwise:
- Length: Must be between 8 and 20 characters, inclusive.
- Complexity: Must contain at least one uppercase letter, one lowercase letter, one digit, and one special character (from the set
!@#$%^&*). - Repetition: Must not contain three or more consecutive identical characters (e.g., "aaa" is invalid).
Function Signature
def is_valid_password(password: str) -> bool:
Examples
Example 1:
Input: password = "Abc1!def"
Output: True
Explanation: Length is 8, contains all required character types, and no three consecutive identical characters exist.
Example 2:
Input: password = "AAAbc123!"
Output: False
Explanation: Contains three consecutive 'A's, which violates the repetition rule.
Constraints
- The string will contain only ASCII characters.
- The password length is at most 100 characters.
Edge Cases
- Empty strings or strings with length < 8.
- Strings with characters outside the specified special set.
- Strings with exactly 20 characters.
Hints
Hint 1
Check the length constraint first to return early if the password is too short or too long.
Hint 2
Use a set or a boolean flag for each complexity requirement and update them while iterating through the string once.
Hint 3
To check for three consecutive identical characters, maintain a counter or compare the current character with the two previous characters.
Follow-up questions
- How would you modify your solution to allow a custom set of prohibited special characters?
- If you needed to check against a large dictionary of banned passwords (e.g., '123456', 'password'), how would you optimize the validation?
- How could you implement this using Regular Expressions, and what are the performance trade-offs compared to the iterative approach?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.