Feature Flag Rollout Validator with Dependency Cycle Detection
Trees & GraphsModel answerLast updated
Parse feature dependency specs, run modular checksum verification, and evaluate user eligibility and feature graph dependencies while handling cyclic rollouts.
This assessment consists of two distinct software components: a string hash generator and a feature rollout validation engine.
Component 1: Email Token Hash Generation
Implement a function build_verification_string(email: str, verification: str, k: int) -> str.
Parameters & Mapping Rules:
email: A string consisting solely of lowercase ASCII characters ('a'to'z') and the symbol characters':','/', and'.'.- Character values map as follows:
'a'through'z'$\rightarrow 1$ to $26$':'$\rightarrow 27$'/'$\rightarrow 28$'.'$\rightarrow 29$
verification: A non-empty string used as an index-lookup table.k: A positive integer indicating block size.
Algorithm:
- Process
emailsequentially in non-overlapping blocks of lengthkfrom left to right. The trailing block may have a length less thank. - For each block, calculate the checksum as the sum of character values in that block.
- Compute the zero-based lookup index via
checksum % len(verification). - Append
verification[index]to the result sequence. - Return the concatenated string.
Component 2: Feature Rollout Dependency Evaluator
Implement a system to evaluate whether a specific feature flag (target_feature) can be safely enabled for a given User.
Data Models
-
User:country:strplatform:str("android"or"ios")version:intenabled_features:set[str](features already active for this user)
-
FeatureRule:allowed_countries:set[str]min_android_version:intmin_ios_version:int
-
ResultDecision:enabled:boolreason:str
Required Rule Ordering & Rejection Reasons
Evaluate target_feature strictly in the following sequence:
-
Eligibility Evaluation:
- Verify country permission:
user.countrymust be inrule.allowed_countries. - Verify platform version:
- For
"android":user.version >= rule.min_android_version. - For
"ios":user.version >= rule.min_ios_version. - Any invalid/unsupported platform fails this check.
- For
- Rejection Logic:
- If only country eligibility fails, return
ResultDecision(False, "COUNTRY_NOT_ALLOWED"). - If only platform/version eligibility fails, return
ResultDecision(False, "PLATFORM_VERSION_NOT_SUPPORTED"). - If both country and platform checks fail, return
ResultDecision(False, "COUNTRY_AND_PLATFORM_NOT_ALLOWED").
- If only country eligibility fails, return
- Verify country permission:
-
Dependency Resolution:
- Dependency verification must only occur if both country and platform checks succeed. If eligibility fails, dependencies must not be parsed or traversed.
- Parse the raw dependency text configuration. Lines are formatted as:
feature_name: dep1, dep2, dep3- Strip outer whitespace around feature names and individual dependencies.
- Split dependencies properly by comma. Empty dependencies or missing right-hand sides must resolve to an empty list.
- A dependency
Dis satisfied if:Dis already present inuser.enabled_features, ORDis included inrollout_features(the current batch of new rollouts) AND all ofD's downstream dependencies are also satisfied.
- If a dependency
Dis neither inuser.enabled_featuresnor inrollout_features, returnResultDecision(False, f"MISSING_DEPENDENCY: {D}"). - If a dependency loop is encountered during traversal, return
ResultDecision(False, f"CYCLE: {cycle_path}"), wherecycle_pathlists the path starting at the first repeated node and returning to itself (e.g.,"CYCLE: A -> B -> C -> A").
-
Success:
- If all checks pass, return
ResultDecision(True, "ENABLED").
- If all checks pass, return
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Analysis
This problem consists of two tasks with explicit validation and logical ordering requirements.
Task 1: Email Verification Hash String
The algorithm takes a string email and steps through it in windows of size k.
- We assign character weights using a lookup function (
'a'-'z'$\rightarrow 1\dots 26$,':'$\rightarrow 27$,'/'$\rightarrow 28$,'.'$\rightarrow 29$). - In Python, string slicing
email[i : i + k]automatically handles the shorter final block. - Summing the weights and taking
checksum % len(verification)yields the correct zero-based index for indexing intoverification.
Task 2: Feature Rollout Dependency Evaluator
The evaluator demands strict order of operations:
-
Gatekeeping Rejections (Eligibility First): Evaluate both
country_okandplatform_okcompletely before returning. A common trap is returning early oncountry_ok == False, which prevents detecting when both checks fail simultaneously (required to return"COUNTRY_AND_PLATFORM_NOT_ALLOWED"). -
Dependency Parsing: Lines are formatted as
feature: dep1, dep2. We split each line at the first colon (partition(':')), then split the right-hand side by,. We must strip whitespace from each token and filter out empty entries. -
Graph Traversal & Cycle Detection: We perform Depth-First Search (DFS) starting from
target_feature.- Satisfied via Enabled: If dependency
dis already inuser.enabled_features, it is satisfied. We don't need to traverse further along that branch. - Missing Dependency: If
dis not inuser.enabled_featuresand not inrollout_features, traversal halts immediately with"MISSING_DEPENDENCY: <d>". - Cycle Detection: We maintain a path vector and a map from feature name to its index in the current recursion path (
path_index). If nodedis found inpath_index, a cycle exists. The cycle path starts atpath_index[d]and appendsdagain at the end (e.g.,A -> B -> C -> A). - Memoization: Nodes fully validated as satisfied can be added to a
memoset so they are not re-evaluated if reached via alternative graph paths.
- Satisfied via Enabled: If dependency
Python 3 Implementation
from dataclasses import dataclass, field
from typing import Dict, List, Set, Optional, Tuple
# Task 1 Implementation
SPECIAL_WEIGHTS = {":": 27, "/": 28, ".": 29}
def get_char_weight(c: str) -> int:
if "a" <= c <= "z":
return ord(c) - ord("a") + 1
if c in SPECIAL_WEIGHTS:
return SPECIAL_WEIGHTS[c]
raise ValueError(f"Invalid character in input: {c}")
def build_verification_string(email: str, verification: str, k: int) -> str:
if not verification:
raise ValueError("Verification lookup table cannot be empty.")
result = []
mod = len(verification)
for i in range(0, len(email), k):
chunk = email[i:i + k]
checksum = sum(get_char_weight(c) for c in chunk)
result.append(verification[checksum % mod])
return "".join(result)
# Task 2 Implementation
@dataclass
class User:
country: str
platform: str
version: int
enabled_features: Set[str] = field(default_factory=set)
@dataclass
class FeatureRule:
allowed_countries: Set[str]
min_android_version: int
min_ios_version: int
@dataclass
class ResultDecision:
enabled: bool
reason: str
SUPPORTED_PLATFORMS = {"android", "ios"}
def parse_dependencies(raw_text: str) -> Dict[str, List[str]]:
deps: Dict[str, List[str]] = {}
for line in raw_text.splitlines():
line = line.strip()
if not line:
continue
feature, sep, raw_deps = line.partition(":")
feature = feature.strip()
if not feature:
continue
if sep:
parsed = [d.strip() for d in raw_deps.split(",") if d.strip()]
deps[feature] = parsed
else:
deps[feature] = []
return deps
def check_platform_eligibility(user: User, rule: FeatureRule) -> bool:
if user.platform not in SUPPORTED_PLATFORMS:
return False
if user.platform == "android":
return user.version >= rule.min_android_version
if user.platform == "ios":
return user.version >= rule.min_ios_version
return False
def evaluate_feature_rollout(
user: User,
rule: FeatureRule,
target_feature: str,
rollout_features: Set[str],
raw_dependencies_text: str
) -> ResultDecision:
# Step 1: Gatekeeping Eligibility Checks
country_ok = user.country in rule.allowed_countries
platform_ok = check_platform_eligibility(user, rule)
if not country_ok and not platform_ok:
return ResultDecision(False, "COUNTRY_AND_PLATFORM_NOT_ALLOWED")
if not country_ok:
return ResultDecision(False, "COUNTRY_NOT_ALLOWED")
if not platform_ok:
return ResultDecision(False, "PLATFORM_VERSION_NOT_SUPPORTED")
# Step 2: Parse Dependencies (Only if eligible)
dependencies = parse_dependencies(raw_dependencies_text)
# Step 3: Graph Traversal & Cycle Detection
memo: Set[str] = set()
path: List[str] = []
path_index: Dict[str, int] = {}
def dfs(curr: str) -> Optional[ResultDecision]:
if curr in user.enabled_features:
return None # Satisfied by user state
if curr in path_index:
# Cycle detected starting from path_index[curr]
cycle_nodes = path[path_index[curr]:] + [curr]
cycle_str = " -> ".join(cycle_nodes)
return ResultDecision(False, f"CYCLE: {cycle_str}")
if curr not in rollout_features:
return ResultDecision(False, f"MISSING_DEPENDENCY: {curr}")
if curr in memo:
return None
path_index[curr] = len(path)
path.append(curr)
for dep in dependencies.get(curr, []):
failure = dfs(dep)
if failure:
return failure
path.pop()
del path_index[curr]
memo.add(curr)
return None
failure_decision = dfs(target_feature)
if failure_decision:
return failure_decision
return ResultDecision(True, "ENABLED")
Complexity Analysis
-
Task 1 (Email Verification):
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the length of
email, since every character is processed once. - Space Complexity: $\mathcal{O}(N / k)$ for the output sequence.
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the length of
-
Task 2 (Feature Rollout Evaluator):
- Time Complexity:
- Parsing: $\mathcal{O}(L)$ where $L$ is the length of the dependency config string.
- Evaluation: $\mathcal{O}(V + E)$ where $V$ is the number of features and $E$ is the number of dependency edges. Node memoization guarantees each sub-graph is traversed at most once.
- Space Complexity: $\mathcal{O}(V + E)$ to store graph structures, recursion stack, and memoization sets.
- Time Complexity: