Katkat

Validate a Password Against Explicit Security Rules

DRWData Engineer · Online Assessment

Last 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:

  1. Length: Must be between 8 and 20 characters (inclusive).
  2. Digit: Must contain at least one digit (0-9).
  3. Lowercase: Must contain at least one lowercase letter (a-z).
  4. Uppercase: Must contain at least one uppercase letter (A-Z).
  5. Special Character: Must contain at least one character from the following set: !@#$%^&*().
  6. No Spaces: Must not contain any whitespace characters.
  7. 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

  • password length is between 0 and 100.
  • password can 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?