Password Strength Problem
#3941
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3941.
You are given a string password.
The strength of the password is calculated based on the following rules:
- 1 point for each distinct lowercase letter (
'a'to'z'). - 2 points for each distinct uppercase letter (
'A'to'Z'). - 3 points for each distinct digit (
'0'to'9'). - 5 points for each distinct special character from the set
"!@#$".
Each character contributes at most once, even if it appears multiple times.
Return an integer denoting the strength of the password.
Example 1:
Input: password = "aA1!"
Output: 11
Explanation:
- The distinct characters are 'a', 'A', '1' and '!'.
- Thus, the strength = 1 + 2 + 3 + 5 = 11.
Example 2:
Input: password = "bbB11#"
Output: 11
Explanation:
- The distinct characters are 'b', 'B', '1' and '#'.
- Thus, the strength = 1 + 2 + 3 + 5 = 11.
Constraints:
1 <= password.length <= 10^5passwordconsists of lowercase and uppercase English letters, digits, and special characters from"!@#$".
Solution
Approach: Distinct Characters
Each distinct character counts once, so we first collect the characters into a set. Then we add the points by kind: 1 for a lowercase letter, 2 for an uppercase letter, 3 for a digit, and 5 for anything else (the only other characters are !@#$).
Complexity: O(n) time and O(1) extra space, since the set holds at most 66 different characters.
class Solution:
def passwordStrength(self, password: str) -> int:
st = set(password)
ans = 0
for ch in st:
if ch.islower():
ans += 1
elif ch.isupper():
ans += 2
elif ch.isdigit():
ans += 3
else:
ans += 5
return ans