#2299
Strong Password Checker II
EasyStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
We can achieve better performance by checking all conditions in a single pass through the password string. This way, we only need to iterate through the string once, making it more efficient.
⚙️
Algorithm
4 steps- 1Step 1: Check if the password length is at least 8 characters.
- 2Step 2: Initialize flags for lowercase, uppercase, digit, special character, and a variable to track the last character.
- 3Step 3: Iterate through each character in the password, updating the flags based on the character type and checking for adjacent duplicates.
- 4Step 4: After the loop, verify if all flags are true.
solution.py19 lines
1def strongPasswordCheckerII(password):
2 if len(password) < 8:
3 return False
4 has_lower = has_upper = has_digit = has_special = False
5 special_characters = "!@#$%^&*()-+"
6 last_char = ''
7 for char in password:
8 if char.islower():
9 has_lower = True
10 elif char.isupper():
11 has_upper = True
12 elif char.isdigit():
13 has_digit = True
14 elif char in special_characters:
15 has_special = True
16 if char == last_char:
17 return False
18 last_char = char
19 return has_lower and has_upper and has_digit and has_specialℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the password string. The space complexity is O(1) since we only use a fixed number of variables.
- 1Checking all conditions in a single pass is more efficient than multiple passes.
- 2Using flags for character types allows for quick validation of password strength.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.