#420

Strong Password Checker

Hard
StringGreedyHeap (Priority Queue)Greedy algorithms for making optimal replacements.Character counting for checking types and repeats.
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach efficiently checks the password's length and character types while managing replacements for repeating characters. It minimizes operations by addressing excess characters directly and adjusting counts based on the password's length.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the number of lowercase letters, uppercase letters, digits, and the number of repeating character sequences.
  2. 2Step 2: Determine how many characters need to be added or removed based on the length of the password.
  3. 3Step 3: Calculate the total number of replacements needed to meet all conditions and return the total adjustments.
solution.py23 lines
1def strongPasswordChecker(password):
2    n = len(password)
3    has_lower = any(c.islower() for c in password)
4    has_upper = any(c.isupper() for c in password)
5    has_digit = any(c.isdigit() for c in password)
6    missing_types = 3 - (has_lower + has_upper + has_digit)
7    repeat_count = 0
8    i = 2
9    while i < n:
10        if password[i] == password[i - 1] == password[i - 2]:
11            repeat_count += 1
12            i += 2
13        else:
14            i += 1
15    if n < 6:
16        return max(6 - n, missing_types)
17    elif n <= 20:
18        return max(repeat_count, missing_types)
19    else:
20        excess = n - 20
21        replacements = excess
22        repeat_count -= min(repeat_count, excess)
23        return replacements + max(repeat_count, missing_types)

Complexity note: The optimal solution runs in O(n) time because it only requires a single pass through the password to check conditions, making it efficient for larger inputs.

  • 1Understanding the conditions for a strong password is crucial for efficiently checking and modifying it.
  • 2Handling edge cases, such as passwords that are too short or too long, is essential for a comprehensive solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.