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:
"rule_1"(Minimum length):pmust have strictly more than15characters (len(p) >= 16)."rule_2"(Banned word):pmust not contain the contiguous substring"password"under case-insensitive matching."rule_3"(Mixed ASCII letter case):pmust contain at least one ASCII uppercase letter ('A'–'Z') and at least one ASCII lowercase letter ('a'–'z')."rule_4"(Required special symbol):pmust contain at least one character from the caller-provided 3-symbol listspecial_chars."rule_5"(Run-length cap): No character may appear5or more times consecutively (up to4identical 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
pmay be any string (including"") containing ASCII or Unicode charactersspecial_charscontains3single-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
Understand the five rules and output format
Given a candidate password
pand a list of three allowed special charactersspecial_chars, we need to return every rule thatpbreaks, using the codes"rule_1"through"rule_5"in rule-number order:Code Valid password requirement Violation condition rule_1Length strictly greater than 15 ( >= 16)len(p) <= 15rule_2Does not contain "password"(any case)"password" in p.lower()rule_3Has at least one A-Zand at least onea-zMissing A-Zor missinga-zrule_4Has at least one symbol from special_charsZero characters from special_charsrule_5At 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.
- Never return early: In Example 1,
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 (16is 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". Convertingpto lowercase once withp.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")- Rule 1 (
Check Rule 3: ASCII uppercase and lowercase letters
Rule 3 specifically asks for at least one uppercase letter from
A-Zand at least one lowercase letter froma-z.In Python,
ch.isupper()andch.islower()check Unicode letter categories, so'É'.isupper()returnsTrueeven though'É'is outsideA-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_lowerCheck Rule 4: at least one caller-supplied special symbol
Notice that
special_charsis passed in dynamically by the caller! As Example 2 illustrates, when the caller passes["$", "%", "&"],'!'does not count as an accepted special symbol.Converting
special_charsinto a set (allowed_specials = set(special_chars)) lets us test each character ofpasswordinO(1)time and returnTrueon 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 FalseCheck Rule 5: longest consecutive character run
Rule 5 says no character (letter, digit, space, or symbol) may appear
5or more times back to back:"zzzz"has run length4(allowed), whereas"77777"or"99999"has run length5(violation).We scan from left to right keeping three variables: -
prev_char: the character at the previous index (Nonebefore index0), -current_run: how many timesprev_charhas appeared back to back right now, -max_run: the largestcurrent_runseen 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_runinside the loop on every step (rather than only whench != 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_runCombine 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) -> []Full solution
Putting the three helper functions together with
validate_passwordgives 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). Buildingallowed_specials = set(special_chars)takesO(k)time.len(p)isO(1),p.lower()and searching for the fixed 8-character string"password"takeO(n), and the three helper functions each scan at mostncharacters doingO(1)work per character. - Space:
O(n + k).p.lower()allocates a lowercase string copy of lengthn,allowed_specialsstores at mostksymbols, andviolationsholds at most5rule strings.
Edge cases
- Empty string
"": Length is0(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 is0-> returns["rule_1", "rule_3", "rule_4"]. - Exact length boundary (
15vs.16): A 15-character password violatesrule_1; a 16-character password satisfies it. - Exact repeat boundary (
4vs.5):"zzzz"(max_run == 4) is valid, whereas"77777"or"99999"(max_run == 5) violatesrule_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 ASCIIA-Zanda-z. - Custom
special_charslist:'!'does not satisfy Rule 4 whenspecial_charsis['$', '%', '&']. - 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) < 15instead oflen(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'É', whilep.isupper()checks whether every cased character in the entire string is uppercase. - Hard-coding a fixed symbol set: Ignores the
special_charsparameter passed by the caller. - Updating
max_runonly inside theelsebranch whench != prev_char: Fails whenever the offending 5-character streak runs all the way to the end ofpwithout a trailing different character to flush it. - Storing violations in a
set: Loses the deterministicrule_1..rule_5ordering.
Follow-up questions
- How would you structure the validator so twenty configurable rules can be added or reordered without turning
validate_passwordinto a long chain ofifstatements? Represent each rule as a small object or(rule_code, predicate_fn)tuple stored in an ordered list, wherepredicate_fn(p)returnsTruewhenppasses the rule.validate_passwordthen becomes a 4-line loop over that list, making it trivial to add, reorder, or parameterize rules (such asmin_length=16ormax_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 (\1matches the exact same character captured by(.)four more times, andre.DOTALLensures.also matches newline'\n'), whilere.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, andre.IGNORECASEfolds 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 bothnormalizedandnormalized[::-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
- 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?
- What are the pros and cons of implementing these five checks with regular expressions instead of explicit character loops?
- How could attackers bypass the forbidden-word rule with character substitutions like `P@ssw0rd`, and how do production auth systems defend against weak passwords?
Similar questions
- Link Order User IDs to Customer Names
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One