Check Password Policy Violations

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement validate_password(p: str, special_chars: List[str]) -> List[str] to evaluate a candidate string p against five independent security policy checks and return the codes of all violated checks in ascending numerical order ("rule_1" through "rule_5").

A compliant password must satisfy every condition below:

  1. "rule_1" (Minimum length): p must have strictly more than 15 characters (len(p) >= 16).
  2. "rule_2" (Banned word): p must not contain the contiguous substring "password" under case-insensitive matching.
  3. "rule_3" (Mixed ASCII letter case): p must contain at least one ASCII uppercase letter ('A'–'Z') and at least one ASCII lowercase letter ('a'–'z').
  4. "rule_4" (Required special symbol): p must contain at least one character from the caller-provided 3-symbol list special_chars.
  5. "rule_5" (Run-length cap): No character may appear 5 or more times consecutively (up to 4 identical adjacent characters is valid).

Return [] when p passes all five checks.

def validate_password(p: str, special_chars: List[str]) -> List[str]:
    ...

Examples

Example 1

Input:  p = "goPassWord77777", special_chars = ["$", "%", "&"]
Output: ["rule_1", "rule_2", "rule_4", "rule_5"]

p has 15 characters (<= 15, failing "rule_1"), embeds "PassWord" ("rule_2"), includes none of "$", "%", or "&" ("rule_4"), and ends with five consecutive '7' characters ("rule_5"). Only "rule_3" passes ('P' and 'g').

Example 2

Input:  p = "quiet_harbor!2026", special_chars = ["$", "%", "&"]
Output: ["rule_3", "rule_4"]

p has length 17, omits "password", and has no repeated run above 1, but lacks an ASCII uppercase letter ("rule_3") and uses '!' instead of a symbol from ["$", "%", "&"] ("rule_4").

Example 3

Input:  p = "Cobalt#Riveraaaa99999", special_chars = ["#", "@", "?"]
Output: ["rule_5"]

Four 'a's in a row is permitted, whereas five '9's in a row exceeds the 4-character streak limit ("rule_5").

Example 4

Input:  p = "Cobalt#River2026zzzz", special_chars = ["#", "@", "?"]
Output: []

Length is 20, "password" does not appear, both 'C' and 'o' are present, '#' belongs to special_chars, and "zzzz" has length 4 <= 4, so zero rules are violated.

Constraints

  • p may be any string (including "") containing ASCII or Unicode characters
  • special_chars contains 3 single-character strings specifying the accepted special symbols for "rule_4"
  • "rule_2" is case-insensitive, "rule_3" checks ASCII 'A'–'Z' and 'a'–'z', and "rule_5" compares exact adjacent characters
  • Violated codes must be returned in ascending order ["rule_1", ..., "rule_5"]

Step-by-step walkthrough

  1. Understand the five rules and output format

    Given a candidate password p and a list of three allowed special characters special_chars, we need to return every rule that p breaks, using the codes "rule_1" through "rule_5" in rule-number order:

    Code Valid password requirement Violation condition
    rule_1 Length strictly greater than 15 (>= 16) len(p) <= 15
    rule_2 Does not contain "password" (any case) "password" in p.lower()
    rule_3 Has at least one A-Z and at least one a-z Missing A-Z or missing a-z
    rule_4 Has at least one symbol from special_chars Zero characters from special_chars
    rule_5 At most 4 identical characters in a row Longest consecutive run > 4 (>= 5)

    Two structural habits keep the implementation clean and bug-free:

    • Never return early: In Example 1, "goPassWord77777" returns ["rule_1", "rule_2", "rule_4", "rule_5"]. Stopping at the first broken rule would miss the remaining three violations.
    • Check in order rule_1 -> rule_5: Evaluating the five independent rules sequentially builds the output list in deterministic order automatically, with no sorting needed.
  2. Check Rule 1 (length) and Rule 2 (forbidden substring)

    Both of the first two rules have classic off-by-one or casing traps:

    • Rule 1 (> 15): "Strictly more than 15" means 15 characters is still too short (16 is the shortest valid password, as seen in Example 1's 15-character input). So the violation check must use <= 15, not < 15.
    • Rule 2 (case-insensitive "password"): Checking only "password" and "Password" would miss mixed-case inputs like "goPassWord77777" or "pAsSwOrD". Converting p to lowercase once with p.lower() folds all 256 possible upper/lower combinations of "password" into "password", so a single substring check "password" in p.lower() catches every one of them.
        # Rule 1: Length must be strictly greater than 15 (16+ characters), so <= 15 is a violation.
        if len(p) <= 15:
            violations.append("rule_1")
    
        # Rule 2: Must not contain "password" in any uppercase/lowercase combination.
        if "password" in p.lower():
            violations.append("rule_2")
    
  3. Check Rule 3: ASCII uppercase and lowercase letters

    Rule 3 specifically asks for at least one uppercase letter from A-Z and at least one lowercase letter from a-z.

    In Python, ch.isupper() and ch.islower() check Unicode letter categories, so 'É'.isupper() returns True even though 'É' is outside A-Z. Comparing character codes directly with "A" <= ch <= "Z" and "a" <= ch <= "z" enforces the exact ASCII letter ranges stated in the rule.

    def has_ascii_upper_and_lower(password: str) -> bool:
        """Return True if password contains at least one 'A'-'Z' and at least one 'a'-'z'."""
        found_upper = False
        found_lower = False
        for ch in password:
            # Compare ASCII ranges directly; str.isupper() also accepts non-ASCII letters like 'É'.
            if "A" <= ch <= "Z":
                found_upper = True
            elif "a" <= ch <= "z":
                found_lower = True
        return found_upper and found_lower
    
  4. Check Rule 4: at least one caller-supplied special symbol

    Notice that special_chars is passed in dynamically by the caller! As Example 2 illustrates, when the caller passes ["$", "%", "&"], '!' does not count as an accepted special symbol.

    Converting special_chars into a set (allowed_specials = set(special_chars)) lets us test each character of password in O(1) time and return True on the first match.

    from typing import List, Set
    
    
    def has_allowed_special(password: str, special_chars: List[str]) -> bool:
        """Return True if password contains at least one character from special_chars."""
        # allowed_specials: set of caller-provided symbols, e.g. {"$","%","&"}, for O(1) lookup.
        allowed_specials: Set[str] = set(special_chars)
        for ch in password:
            if ch in allowed_specials:
                return True
        return False
    
  5. Check Rule 5: longest consecutive character run

    Rule 5 says no character (letter, digit, space, or symbol) may appear 5 or more times back to back: "zzzz" has run length 4 (allowed), whereas "77777" or "99999" has run length 5 (violation).

    We scan from left to right keeping three variables: - prev_char: the character at the previous index (None before index 0), - current_run: how many times prev_char has appeared back to back right now, - max_run: the largest current_run seen anywhere in the string.

    Watch how those variables evolve when a 5-character streak sits right at the end of "Ab$77777":

    Index:        0     1     2     3     4     5     6     7
    Char (ch):   'A'   'b'   '$'   '7'   '7'   '7'   '7'   '7'
    prev_char:   'A'   'b'   '$'   '7'   '7'   '7'   '7'   '7'
    current_run:  1     1     1     1     2     3     4     5
    max_run:      1     1     1     1     2     3     4     5  --> 5 > 4 (violates rule_5!)
    

    Updating max_run inside the loop on every step (rather than only when ch != prev_char) guarantees we never miss a streak that reaches the end of the string.

    from typing import Optional
    
    
    def max_consecutive_repeats(password: str) -> int:
        """Return the length of the longest contiguous run of identical characters."""
        # Track the active streak (e.g. "aaab" -> current_run = 1, 2, 3, 1) and the best seen so far.
        max_run = 0
        current_run = 0
        prev_char: Optional[str] = None
    
        for ch in password:
            if ch == prev_char:
                current_run += 1
            else:
                current_run = 1
                prev_char = ch
    
            # Update max_run on every character so a run reaching the end of the string is captured.
            if current_run > max_run:
                max_run = current_run
    
        return max_run
    
  6. Combine all five checks and trace the examples

    Let's walk three of the examples through all five checks:

    Example 1: p = "goPassWord77777" (length 15), special_chars = ["$", "%", "&"]
      rule_1: len(p) = 15 <= 15                 -> VIOLATED ("rule_1")
      rule_2: "password" in "gopassword77777"   -> VIOLATED ("rule_2")
      rule_3: has 'P' (A-Z) and 'g' (a-z)       -> ok
      rule_4: no '$', '%', or '&'               -> VIOLATED ("rule_4")
      rule_5: max_consecutive_repeats = 5       -> VIOLATED ("rule_5")
      => ["rule_1", "rule_2", "rule_4", "rule_5"]
    
    Example 2: p = "quiet_harbor!2026" (length 17), special_chars = ["$", "%", "&"]
      rule_1: len(p) = 17 > 15                  -> ok
      rule_2: "password" absent                 -> ok
      rule_3: has 'a'-'z', missing 'A'-'Z'      -> VIOLATED ("rule_3")
      rule_4: '!' is not in ["$", "%", "&"]     -> VIOLATED ("rule_4")
      rule_5: max_consecutive_repeats = 1       -> ok
      => ["rule_3", "rule_4"]
    
    Example 4: p = "Cobalt#River2026zzzz" (length 20), special_chars = ["#", "@", "?"]
      All 5 checks pass (max_run = 4 <= 4)      -> []
    
  7. Full solution

    Putting the three helper functions together with validate_password gives the complete solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def has_ascii_upper_and_lower(password: str) -> bool:
        """Return True if password contains at least one 'A'-'Z' and at least one 'a'-'z'."""
        found_upper = False
        found_lower = False
        for ch in password:
            # Compare ASCII ranges directly; str.isupper() also accepts non-ASCII letters like 'É'.
            if "A" <= ch <= "Z":
                found_upper = True
            elif "a" <= ch <= "z":
                found_lower = True
        return found_upper and found_lower
    
    
    def has_allowed_special(password: str, special_chars: List[str]) -> bool:
        """Return True if password contains at least one character from special_chars."""
        # allowed_specials: set of caller-provided symbols, e.g. {"$","%","&"}, for O(1) lookup.
        allowed_specials: Set[str] = set(special_chars)
        for ch in password:
            if ch in allowed_specials:
                return True
        return False
    
    
    def max_consecutive_repeats(password: str) -> int:
        """Return the length of the longest contiguous run of identical characters."""
        # Track the active streak (e.g. "aaab" -> current_run = 1, 2, 3, 1) and the best seen so far.
        max_run = 0
        current_run = 0
        prev_char: Optional[str] = None
    
        for ch in password:
            if ch == prev_char:
                current_run += 1
            else:
                current_run = 1
                prev_char = ch
    
            # Update max_run on every character so a run reaching the end of the string is captured.
            if current_run > max_run:
                max_run = current_run
    
        return max_run
    
    
    def validate_password(p: str, special_chars: List[str]) -> List[str]:
        # Collect every violated rule code in ascending rule order (never return early).
        violations: List[str] = []
    
        # Rule 1: Length must be strictly greater than 15 (16+ characters), so <= 15 is a violation.
        if len(p) <= 15:
            violations.append("rule_1")
    
        # Rule 2: Must not contain "password" in any uppercase/lowercase combination.
        if "password" in p.lower():
            violations.append("rule_2")
    
        # Rule 3: Must contain both an ASCII uppercase letter and an ASCII lowercase letter.
        if not has_ascii_upper_and_lower(p):
            violations.append("rule_3")
    
        # Rule 4: Must contain at least one character from the caller's special_chars list.
        if not has_allowed_special(p, special_chars):
            violations.append("rule_4")
    
        # Rule 5: Up to 4 identical characters in a row is valid; 5 or more violates the rule.
        if max_consecutive_repeats(p) > 4:
            violations.append("rule_5")
    
        return violations
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of password validation like a safety inspector walking down a five-box checklist on a clipboard. Even if item #1 fails right away, a good inspector still checks items #2 through #5 from top to bottom so the person submitting the form gets the complete list of fixes needed in one pass, always listed in checklist order (rule_1 through rule_5).

Why do quick-and-dirty implementations stumble on a problem this direct? First, returning as soon as one check fails hides every later violation. Second, hard-coding assumptions — checking only "password" and "Password" instead of a case-insensitive (ignoring uppercase vs. lowercase differences) substring (a contiguous slice of characters inside a string) search, or hard-coding fixed punctuation instead of reading special_chars — breaks on mixed-case words like "pAsSwOrD" and custom symbol lists. Third, subtle boundary mistakes like writing len(p) < 15 instead of <= 15, calling Unicode .isupper() instead of checking ASCII character ranges ("A" <= ch <= "Z", which test standard English letters by their numeric character codes), or forgetting to update the run-length (the count of identical back-to-back characters) at the final character of the string cause off-by-one bugs. Putting special_chars into a hash set (a Python set supporting O(1) average membership checks) and writing one clean helper per rule keeps every boundary crystal clear.

Let's trace Example 1 (p = "goPassWord77777", special_chars = ["$", "%", "&"]):

Input: p = "goPassWord77777" (15 chars), special_chars = ["$", "%", "&"]

1. Rule 1 (len > 15):       15 <= 15                         -> append "rule_1"
2. Rule 2 (no "password"):  "password" in "gopassword77777"  -> append "rule_2"
3. Rule 3 (A-Z and a-z):    sees 'P' (upper) and 'g' (lower) -> pass
4. Rule 4 (special symbol): none of '$', '%', '&' present    -> append "rule_4"
5. Rule 5 (max run <= 4):   trailing "77777" has length 5    -> append "rule_5"

Output: ["rule_1", "rule_2", "rule_4", "rule_5"]

Complexity

Let n be the length of the password p and k be the number of characters in special_chars (k = 3 here).

  • Time: O(n + k). Building allowed_specials = set(special_chars) takes O(k) time. len(p) is O(1), p.lower() and searching for the fixed 8-character string "password" take O(n), and the three helper functions each scan at most n characters doing O(1) work per character.
  • Space: O(n + k). p.lower() allocates a lowercase string copy of length n, allowed_specials stores at most k symbols, and violations holds at most 5 rule strings.

Edge cases

  • Empty string "": Length is 0 (rule_1), has neither uppercase nor lowercase letters (rule_3), and has no special character (rule_4), while "password" is absent and the longest run is 0 -> returns ["rule_1", "rule_3", "rule_4"].
  • Exact length boundary (15 vs. 16): A 15-character password violates rule_1; a 16-character password satisfies it.
  • Exact repeat boundary (4 vs. 5): "zzzz" (max_run == 4) is valid, whereas "77777" or "99999" (max_run == 5) violates rule_5, even when the 5-character streak appears at the very end of the string or consists of digits, spaces, or symbols.
  • Case sensitivity of Rule 5 vs. Rule 2: Only Rule 2 is case-insensitive; "aaAAa" does not violate Rule 5 because 'a' and 'A' are distinct characters.
  • Non-ASCII letters such as 'É' or 'ñ': Excluded from Rule 3 because the specification requires ASCII A-Z and a-z.
  • Custom special_chars list: '!' does not satisfy Rule 4 when special_chars is ['$', '%', '&'].
  • All five rules broken at once: "passwordddddd" returns ["rule_1", "rule_2", "rule_3", "rule_4", "rule_5"].

Common mistakes

  • Returning early on the first failure: Produces a 1-element list instead of reporting all violated rules.
  • Writing len(p) < 15 instead of len(p) <= 15: "Strictly more than 15" requires at least 16 characters, so length 15 must fail.
  • Using ch.isupper() / ch.islower() (or worse, p.isupper()): ch.isupper() accepts non-ASCII uppercase letters like 'É', while p.isupper() checks whether every cased character in the entire string is uppercase.
  • Hard-coding a fixed symbol set: Ignores the special_chars parameter passed by the caller.
  • Updating max_run only inside the else branch when ch != prev_char: Fails whenever the offending 5-character streak runs all the way to the end of p without a trailing different character to flush it.
  • Storing violations in a set: Loses the deterministic rule_1 .. rule_5 ordering.

Follow-up questions

  • How would you structure the validator so twenty configurable rules can be added or reordered without turning validate_password into a long chain of if statements? Represent each rule as a small object or (rule_code, predicate_fn) tuple stored in an ordered list, where predicate_fn(p) returns True when p passes the rule. validate_password then becomes a 4-line loop over that list, making it trivial to add, reorder, or parameterize rules (such as min_length=16 or max_repeat=4) and attach human-readable error messages alongside codes:
rules = [
    ("rule_1", lambda s: len(s) > 15),
    ("rule_2", lambda s: "password" not in s.lower()),
    ("rule_3", has_ascii_upper_and_lower),
    ("rule_4", lambda s: has_allowed_special(s, special_chars)),
    ("rule_5", lambda s: max_consecutive_repeats(s) <= 4),
]
violations = [code for code, passes in rules if not passes(p)]
  • What are the pros and cons of implementing these five checks with regular expressions instead of explicit character loops? Regular expressions are compact — for example, re.search(r"(.)\1{4}", p, re.DOTALL) uses a backreference (\1 matches the exact same character captured by (.) four more times, and re.DOTALL ensures . also matches newline '\n'), while re.escape("".join(special_chars)) safely builds a character class for Rule 4. However, regex backreferences and escaping traps (like '-', ']', or '^' inside [...]) are much easier to get subtly wrong in an interview than plain loops, and re.IGNORECASE folds certain Unicode characters (like 'ſ' matching 's') differently from .lower().
  • How could attackers bypass the forbidden-word rule with character substitutions like P@ssw0rd, and how do production auth systems defend against weak passwords? Apply a normalization table ('@' -> 'a', '0' -> 'o', '$' -> 's', '1' -> 'i', '3' -> 'e') to produce a canonical lowercase string and test both normalized and normalized[::-1] against a blocklist. In production authentication systems, modern security standards (such as NIST SP 800-63B) go further: rather than piling on complex symbol rules, they screen candidate passwords against a hashed set or Bloom filter (a compact probabilistic bit array for fast membership checks) of millions of known breached and dictionary passwords.

Follow-up questions

Similar questions

More Karat interview questions

All 2 Karat questions →