algoadvance

Leetcode Problem #2299

A password is considered strong if the following criteria are all met:

  1. It has at least 8 characters.
  2. It contains at least one lowercase letter.
  3. It contains at least one uppercase letter.
  4. It contains at least one digit.
  5. It contains at least one special character. The special characters are: !@#$%^&*()-+
  6. It does not contain two characters in a row that are the same.

Given a string password, return true if it is strong, otherwise return false.

Clarifying Questions

  1. Q: Can the password contain spaces? A: The problem statement does not mention spaces, so let’s assume the password doesn’t contain spaces.

  2. Q: What should be done if one of the criteria is not met? A: Return false if any single criterion isn’t met.

Strategy

To determine if a password is strong, we will perform the following checks:

  1. Length Check: Ensure the password is at least 8 characters long.
  2. Character Checks: Ensure the password contains at least one lowercase letter, one uppercase letter, one digit, and one special character.
  3. Repeating Characters Check: Ensure no two consecutive characters are the same.

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.

Code

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

Time Complexity

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.

Summary

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.

Try our interview co-pilot at AlgoAdvance.com