Validate a Password Against Explicit Security Rules
DRWData Engineer · Online AssessmentLast updated
This problem tests string manipulation, character set validation, and the ability to apply a sequence of conditional checks efficiently.
Problem Statement
Given a string password, determine if it meets the following security requirements. Return true if it passes all rules, otherwise return false.
Security Requirements:
- Length: Must be between 8 and 20 characters (inclusive).
- Digit: Must contain at least one digit (0-9).
- Lowercase: Must contain at least one lowercase letter (a-z).
- Uppercase: Must contain at least one uppercase letter (A-Z).
- Special Character: Must contain at least one character from the following set:
!@#$%^&*(). - No Spaces: Must not contain any whitespace characters.
- Allowed Characters: The password must not contain any characters other than alphanumeric characters and the specified special character set.
Function Signature
def validate_password(password: str) -> bool:
Examples
Example 1:
Input: password = "Abc1!def"
Output: true
Explanation: Length is 8, contains digit, lowercase, uppercase, and a special character from the allowed set. No illegal characters present.
Example 2:
Input: password = "Abc 1!def"
Output: false
Explanation: Contains a space character.
Example 3:
Input: password = "Abc1!"
Output: false
Explanation: Length is less than 8.
Constraints
passwordlength is between 0 and 100.passwordcan contain any Unicode character.
Hints
Hint 1
You can use a set of valid characters to perform a quick look-up for the final rule.
Hint 2
Iterate through the string once and maintain boolean flags for each requirement (digit, lower, upper, special, etc.).
Hint 3
Ensure you verify that every character in the input string is either alphanumeric or one of the required special characters.
Follow-up questions
- How would you modify your solution if the requirement was to ensure no character repeats more than three times consecutively?
- How would you update the code to allow for a dynamic list of special characters provided as a parameter?
- What is the time complexity of your current solution, and how would you optimize the search for invalid characters?
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.