algoadvance

Leetcode 2299. Strong Password Checker II

Problem Statement

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 2 of the same character in adjacent positions.

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

Clarifying Questions

  1. Case sensitivity: Are the checks case-sensitive for conditions on uppercase and lowercase letters?
    • Assumption: Yes, as per the problem statement.
  2. Special characters: Are the special characters fixed as “!@#$%^&*()-+”?
    • Assumption: Yes, as per the problem statement.

Strategy

To solve this problem, we can perform the following steps:

  1. Check the length of the password to ensure it has at least 8 characters.
  2. Iterate through each character in the password to:
    • Check for the presence of at least one lowercase letter.
    • Check for the presence of at least one uppercase letter.
    • Check for the presence of at least one digit.
    • Check for the presence of at least one special character.
    • Check that no two adjacent characters are the same.
  3. Return true only if all conditions are satisfied.

Code

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

bool strongPasswordCheckerII(string password) {
    if (password.length() < 8) return false;
    
    bool hasLower = false, hasUpper = false, hasDigit = false, hasSpecial = false;
    unordered_set<char> specialChars = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+'};
    
    for (int i = 0; i < password.length(); ++i) {
        char c = password[i];
        
        if (i > 0 && password[i] == password[i - 1]) return false; // No two adjacent characters should be the same
        
        if (islower(c)) hasLower = true;
        if (isupper(c)) hasUpper = true;
        if (isdigit(c)) hasDigit = true;
        if (specialChars.find(c) != specialChars.end()) hasSpecial = true;
    }
    
    return hasLower && hasUpper && hasDigit && hasSpecial;
}

// Example usage:
int main() {
    string password = "Aa1!Aa1!";
    if (strongPasswordCheckerII(password)) {
        cout << "Password is strong." << endl;
    } else {
        cout << "Password is not strong." << endl;
    }
    return 0;
}

Time Complexity

The time complexity of this solution is O(n), where n is the length of the password. This is because we iterate through each character in the password exactly once to check all the conditions.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI