KatInterview

420. Strong Password Checker

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to find the minimum number of operations (insert, delete, replace) to make a given password "strong". A strong password must satisfy three conditions:

Solution

Strong Password Checker in Python

class Solution:
    def strongPasswordChecker(self, password: str) -> int:
        n = len(password)
        
        # Step 1: Count missing character types
        has_lower = any('a' <= c <= 'z' for c in password)
        has_upper = any('A' <= c <= 'Z' for c in password)
        has_digit = any('0' <= c <= '9' for c in password)
        missing_types = 3 - (has_lower + has_upper + has_digit)

        # Case 1: n < 6
        if n < 6:
            # We need at least 6-n insertions.
            # Each insertion can also fix a missing type.
            # So the answer is the maximum of these two requirements.
            return max(6 - n, missing_types)

        # Step 2 for n >= 6: Find repeating sequences and calculate changes.
        # `replaces`: total replacements needed for repeats.
        # `ones`, `twos`: counts of repeat groups that can be fixed with 1 or 2 deletions.
        replaces = 0
        ones = 0  # repeats of length % 3 == 0
        twos = 0  # repeats of length % 3 == 1
        i = 0
        while i < n:
            j = i
            while j < n and password[j] == password[i]:
                j += 1
            length = j - i
            if length >= 3:
                replaces += length // 3
                if length % 3 == 0:
                    ones += 1
                elif length % 3 == 1:
                    twos += 1
            i = j

        # Case 2: 6 <= n <= 20
        if n <= 20:
            # Replacements can fix both repeats and missing types.
            return max(replaces, missing_types)

        # Case 3: n > 20
        deletes = n - 20

        # Greedily use deletions to reduce replacements.
        # Priority 1: Use 1 deletion to fix a (len % 3 == 0) group, saving 1 replacement.
        use1 = min(deletes, ones)
        deletes -= use1
        replaces -= use1
        
        # Priority 2: Use 2 deletions to fix a (len % 3 == 1) group, saving 1 replacement.
        use2 = min(deletes // 2, twos)
        deletes -= use2 * 2
        replaces -= use2
        
        # Priority 3: Use 3 deletions to fix any group, saving 1 replacement.
        use3 = min(deletes // 3, replaces)
        replaces -= use3
        
        # Total ops = mandatory deletions + remaining fixes (replacements or missing types).
        return (n - 20) + max(missing_types, replaces)

Strong Password Checker in Java

class Solution {
    public int strongPasswordChecker(String password) {
        int n = password.length();
        
        // Step 1: Count missing character types
        boolean hasLower = false, hasUpper = false, hasDigit = false;
        for (char c : password.toCharArray()) {
            if (Character.isLowerCase(c)) hasLower = true;
            if (Character.isUpperCase(c)) hasUpper = true;
            if (Character.isDigit(c)) hasDigit = true;
        }
        int missingTypes = (hasLower ? 0 : 1) + (hasUpper ? 0 : 1) + (hasDigit ? 0 : 1);

        // Case 1: n < 6
        if (n < 6) {
            // We need at least 6-n insertions.
            // Each insertion can also fix a missing type.
            // So the answer is the maximum of these two requirements.
            return Math.max(6 - n, missingTypes);
        }
        
        // Step 2 for n >= 6: Find repeating sequences and calculate changes.
        // `replaces`: total replacements needed for repeats.
        // `ones`, `twos`: counts of repeat groups that can be fixed with 1 or 2 deletions.
        int replaces = 0; 
        int ones = 0;     // repeats of length % 3 == 0
        int twos = 0;     // repeats of length % 3 == 1
        
        for (int i = 0; i < n; ) {
            int j = i;
            while (j < n && password.charAt(j) == password.charAt(i)) {
                j++;
            }
            int len = j - i;
            if (len >= 3) {
                replaces += len / 3;
                if (len % 3 == 0) {
                    ones++;
                } else if (len % 3 == 1) {
                    twos++;
                }
            }
            i = j;
        }

        // Case 2: 6 <= n <= 20
        if (n <= 20) {
            // Replacements can fix both repeats and missing types.
            return Math.max(replaces, missingTypes);
        }
        
        // Case 3: n > 20
        int deletes = n - 20;
        
        // Greedily use deletions to reduce replacements.
        // Priority 1: Use 1 deletion to fix a (len % 3 == 0) group, saving 1 replacement.
        int use1 = Math.min(deletes, ones);
        deletes -= use1;
        replaces -= use1;
        
        // Priority 2: Use 2 deletions to fix a (len % 3 == 1) group, saving 1 replacement.
        int use2 = Math.min(deletes / 2, twos);
        deletes -= use2 * 2;
        replaces -= use2;
        
        // Priority 3: Use 3 deletions to fix any group, saving 1 replacement.
        int use3 = Math.min(deletes / 3, replaces);
        replaces -= use3;
        
        // Total ops = mandatory deletions + remaining fixes (replacements or missing types).
        return (n - 20) + Math.max(missingTypes, replaces);
    }
}

Strong Password Checker in C++

class Solution {
public:
    int strongPasswordChecker(string password) {
        int n = password.length();
        
        // Step 1: Count missing character types
        bool has_lower = false, has_upper = false, has_digit = false;
        for (char c : password) {
            if (islower(c)) has_lower = true;
            if (isupper(c)) has_upper = true;
            if (isdigit(c)) has_digit = true;
        }
        int missing_types = (!has_lower) + (!has_upper) + (!has_digit);
        
        // Case 1: n < 6
        if (n < 6) {
            // We need at least 6-n insertions.
            // Each insertion can also fix a missing type.
            // So the answer is the maximum of these two requirements.
            return max(6 - n, missing_types);
        }
        
        // Step 2 for n >= 6: Find repeating sequences and calculate changes.
        // `replaces`: total replacements needed for repeats.
        // `ones`, `twos`: counts of repeat groups that can be fixed with 1 or 2 deletions.
        int replaces = 0;
        int ones = 0; // repeats of length % 3 == 0
        int twos = 0; // repeats of length % 3 == 1
        for (int i = 0; i < n; ) {
            int j = i;
            while (j < n && password[j] == password[i]) {
                j++;
            }
            int len = j - i;
            if (len >= 3) {
                replaces += len / 3;
                if (len % 3 == 0) ones++;
                else if (len % 3 == 1) twos++;
            }
            i = j;
        }
        
        // Case 2: 6 <= n <= 20
        if (n <= 20) {
            // Replacements can fix both repeats and missing types.
            return max(replaces, missing_types);
        }
        
        // Case 3: n > 20
        int deletes = n - 20;
        
        // Greedily use deletions to reduce replacements.
        // Priority 1: Use 1 deletion to fix a (len % 3 == 0) group, saving 1 replacement.
        int use1 = min(deletes, ones);
        deletes -= use1;
        replaces -= use1;
        
        // Priority 2: Use 2 deletions to fix a (len % 3 == 1) group, saving 1 replacement.
        int use2 = min(deletes / 2, twos);
        deletes -= use2 * 2;
        replaces -= use2;
        
        // Priority 3: Use 3 deletions to fix any group, saving 1 replacement.
        int use3 = min(deletes / 3, replaces);
        replaces -= use3;
        
        // Total ops = mandatory deletions + remaining fixes (replacements or missing types).
        return (n - 20) + max(missing_types, replaces);
    }
};

Strong Password Checker in TypeScript

function strongPasswordChecker(password: string): number {
    const n = password.length;

    // Step 1: Count missing character types
    let hasLower = false, hasUpper = false, hasDigit = false;
    for (const char of password) {
        if (char >= 'a' && char <= 'z') hasLower = true;
        if (char >= 'A' && char <= 'Z') hasUpper = true;
        if (char >= '0' && char <= '9') hasDigit = true;
    }
    let missingTypes = (hasLower ? 0 : 1) + (hasUpper ? 0 : 1) + (hasDigit ? 0 : 1);

    // Case 1: n < 6
    if (n < 6) {
        // We need at least 6-n insertions.
        // Each insertion can also fix a missing type.
        // So the answer is the maximum of these two requirements.
        return Math.max(6 - n, missingTypes);
    }

    // Step 2 for n >= 6: Find repeating sequences and calculate changes.
    // `replaces`: total replacements needed for repeats.
    // `ones`, `twos`: counts of repeat groups that can be fixed with 1 or 2 deletions.
    let replaces = 0;
    let ones = 0; // repeats of length % 3 == 0
    let twos = 0; // repeats of length % 3 == 1

    for (let i = 0; i < n; ) {
        let j = i;
        while (j < n && password[j] === password[i]) {
            j++;
        }
        const len = j - i;
        if (len >= 3) {
            replaces += Math.floor(len / 3);
            if (len % 3 === 0) ones++;
            else if (len % 3 === 1) twos++;
        }
        i = j;
    }

    // Case 2: 6 <= n <= 20
    if (n <= 20) {
        // Replacements can fix both repeats and missing types.
        return Math.max(replaces, missingTypes);
    }

    // Case 3: n > 20
    let deletes = n - 20;

    // Greedily use deletions to reduce replacements.
    // Priority 1: Use 1 deletion to fix a (len % 3 == 0) group, saving 1 replacement.
    const use1 = Math.min(deletes, ones);
    deletes -= use1;
    replaces -= use1;

    // Priority 2: Use 2 deletions to fix a (len % 3 == 1) group, saving 1 replacement.
    const use2 = Math.min(Math.floor(deletes / 2), twos);
    deletes -= use2 * 2;
    replaces -= use2;

    // Priority 3: Use 3 deletions to fix any group, saving 1 replacement.
    const use3 = Math.min(Math.floor(deletes / 3), replaces);
    replaces -= use3;

    // Total ops = mandatory deletions + remaining fixes (replacements or missing types).
    return (n - 20) + Math.max(missingTypes, replaces);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.