We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Strong Password Checker II

Number: 2391

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a password string, determine if it is strong by ensuring it meets all of 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 from the set "!@#$%^&*()-+".
  • It does not contain two identical characters in adjacent positions.

Key Insights

  • Validate the minimum length requirement before processing further.
  • Use boolean flags to track the presence of lowercase, uppercase, digits, and special characters.
  • Efficiently detect two identical consecutive characters by comparing the current character to the previous one.
  • Use a set or direct lookup to verify if a character is a special character.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the password. Space Complexity: O(1), since only constant extra space is used for flags and helper structures.


Solution

The solution involves a single pass through the password string to check all the necessary conditions:

  1. Verify if the password meets the minimum length.
  2. Traverse each character:
    • Check for consecutive identical characters.
    • Update flags to confirm the existence of lowercase letters, uppercase letters, digits, and special characters.
  3. After the iteration, validate that all required flags are true.
  4. Return the result accordingly.

Code Solutions

# Function to check if the password is strong
def strongPasswordCheckerII(password: str) -> bool:
    # Check minimum length requirement
    if len(password) < 8:
        return False

    # Define special characters set
    special_chars = set("!@#$%^&*()-+")
    
    # Initialize flags for required characters
    has_lower = False
    has_upper = False
    has_digit = False
    has_special = False

    # Iterate through the password characters
    for i, char in enumerate(password):
        # Check for consecutive identical characters
        if i > 0 and char == password[i - 1]:
            return False
        # Check for lowercase letter
        if char.islower():
            has_lower = True
        # Check for uppercase letter
        elif char.isupper():
            has_upper = True
        # Check for digit
        elif char.isdigit():
            has_digit = True
        # Check for special character
        elif char in special_chars:
            has_special = True

    # Return True if all requirements are met
    return has_lower and has_upper and has_digit and has_special

# Example usage:
print(strongPasswordCheckerII("IloveLe3tcode!"))
← Back to All Questions