Generate Unique Character Profiles with Attribute Rules
Data Structure DesignModel answerLast updated
Build a generator that creates N character profiles from trait pools, enforcing no-duplicates, uniqueness, and dependency rules between attributes.
You are building a character generator for a game. Given a collection of character attributes—each attribute has a name and a list of possible values—you need to generate N complete character profiles.
Input:
attributes: dict[str, list[str]]mapping attribute names to their possible values
Example:{"class": ["warrior", "mage"], "weapon": ["sword", "staff", "bow"]}count: int— number of profiles to generateconstraints: list[tuple]— optional dependency rules (see below)all_distinct: bool— whether every generated profile must be unique
Constraints (applied in order of priority):
- Each profile assigns exactly one value to every attribute
- If
all_distinctis true, no two profiles may share the same complete assignment - Dependency rules:
("must_pair", ("class", "mage"), ("weapon", "staff"))— if class is mage, weapon must be staff("cannot_pair", ("class", "warrior"), ("weapon", "staff"))— if class is warrior, weapon cannot be staff
Output:
Return a list of count profile dictionaries. If generating count valid profiles is impossible, raise an exception with a message explaining why and attach any successfully generated profiles.
Your task: Implement the generator function. Explain your algorithm, data structures, time and space complexity, and how you handle edge cases. Describe what makes this problem hard and what trade-offs you considered.
Hints
Hint 1
Think of each profile as a constraint satisfaction problem; backtracking can explore valid assignments.
Hint 2
Index rules by the attributes they reference so you only check relevant constraints at each step.
Hint 3
Consider when to verify uniqueness: during generation or after? What's the complexity trade-off?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a constraint satisfaction problem where each profile is an assignment of values to attributes. The core challenge is efficiently generating valid, potentially unique assignments under arbitrary dependency rules.
Algorithm: Backtracking with Constraint Propagation
Use depth-first search with backtracking to construct each profile incrementally:
- Process attributes in a fixed order
- For each attribute, try candidate values one at a time
- Check only the constraints involving already-assigned attributes
- Prune branches that violate constraints immediately
- Emit a complete profile when all attributes are assigned
For uniqueness: Run a single DFS traversal and pull N distinct leaves. Each root-to-leaf path in the search tree represents a unique profile, so no separate deduplication is needed.
Without uniqueness: Generate each profile independently with a fresh randomized DFS.
Data Structures
# Deduplicated value lists (preserve order)
values = {attr: list(dict.fromkeys(vals)) for attr, vals in attributes.items()}
# Index constraints by attribute for fast lookup
constraints_by_attr = defaultdict(list)
for constraint in constraints:
kind, (attr1, val1), (attr2, val2) = constraint
constraints_by_attr[attr1].append(constraint)
constraints_by_attr[attr2].append(constraint)
# Current partial assignment (mutated during DFS)
assignment = {}
Why this indexing matters: At each step we only check constraints touching the current attribute, not all R constraints globally. This reduces redundant checks from O(R · attributes) to O(relevant_constraints · attributes).
Implementation Sketch
import random
from collections import defaultdict
class GenerationError(Exception):
def __init__(self, msg, partial_results):
super().__init__(msg)
self.partial = partial_results
def generate_profiles(attributes, count, constraints=None, all_distinct=True, seed=None):
if count == 0:
return []
# Validate and preprocess
attr_names = list(attributes.keys())
values = {a: list(dict.fromkeys(v)) for a, v in attributes.items()}
# Index constraints
rules_by_attr = defaultdict(list)
for rule in (constraints or []):
kind, (a1, v1), (a2, v2) = rule
# Validate rule references known attributes/values
if a1 not in values or v1 not in values[a1]:
raise ValueError(f"Invalid constraint: {a1}={v1}")
if a2 not in values or v2 not in values[a2]:
raise ValueError(f"Invalid constraint: {a2}={v2}")
rules_by_attr[a1].append(rule)
rules_by_attr[a2].append(rule)
rng = random.Random(seed)
def violates_constraint(rule, assignment):
"""Check if current assignment violates this rule"""
kind, (a1, v1), (a2, v2) = rule
# Only check when both attributes assigned
if a1 not in assignment or a2 not in assignment:
return False
if assignment[a1] != v1:
return False
if kind == "must_pair":
return assignment[a2] != v2
else: # cannot_pair
return assignment[a2] == v2
def backtrack(index, assignment):
"""Generate valid assignments via DFS"""
if index == len(attr_names):
yield dict(assignment) # Copy complete assignment
return
current_attr = attr_names[index]
candidates = values[current_attr][:]
rng.shuffle(candidates)
for value in candidates:
assignment[current_attr] = value
# Check constraints involving this attribute
valid = True
for rule in rules_by_attr[current_attr]:
if violates_constraint(rule, assignment):
valid = False
break
if valid:
yield from backtrack(index + 1, assignment)
del assignment[current_attr]
# Generate profiles
results = []
if all_distinct:
# Single traversal for uniqueness
generator = backtrack(0, {})
for profile in generator:
results.append(profile)
if len(results) == count:
break
else:
# Independent generation
for _ in range(count):
generator = backtrack(0, {})
profile = next(generator, None)
if profile is None:
raise GenerationError(
f"No valid profiles exist",
results
)
results.append(profile)
if len(results) < count:
raise GenerationError(
f"Only {len(results)} valid unique profiles exist, requested {count}",
results
)
return results
Complexity Analysis
Let A = number of attributes, V = max values per attribute, C = number of constraints.
Time:
- Worst case: O(V^A · C) — must explore entire search space when few valid profiles exist or to prove impossibility
- Average case: O(count · A · C) when constraints are sparse and most branches succeed
- Early pruning drastically reduces the explored space in practice
Space:
- O(A) for recursion stack and assignment dictionary
- O(count · A) for output
- O(C) for constraint index
Edge Cases and Validation
Empty inputs:
count = 0→ return empty listattributes = {}→ exactly one valid profile exists:{}; requesting more with uniqueness fails
Impossible scenarios:
- Contradictory constraints:
("must_pair", (A, x), (B, y))and("cannot_pair", (A, x), (B, y))— backtracking prunes all branches, returns 0 profiles countexceeds valid combinations withall_distinct=True— raise error with partial results
Data quality:
- Deduplicate value lists upfront (duplicates skew sampling)
- Validate constraint references point to existing attributes/values
- Prevent self-referencing constraints
Trade-offs and Alternatives
Uniformity: Randomized DFS doesn't sample uniformly from the valid space. Branches under heavily-pruned subtrees are over-represented.
- Fix: If valid space is small (< 10^6), enumerate all valid profiles and sample uniformly with
random.sample() - When to use: Fairness matters more than performance
Constraint ordering: Process the most-constrained attributes first (most rules attached). This prunes invalid branches earlier—the "fail-fast" heuristic from CSP literature.
Rejection sampling: For large spaces with few constraints, generate random complete assignments and reject invalids. Works well when valid density is high, but degenerates when constraints are tight.
Caching for non-unique mode: Generate all valid profiles once, cache them, then sample with replacement. Avoids redundant DFS but uses O(valid_space · A) memory.
Testing Strategy
- Basic correctness: Generate small sets, verify all constraints satisfied
- Uniqueness: Check no duplicates in output when
all_distinct=True - Impossibility: Request more profiles than exist, verify exception raised with correct partial count
- Contradictory rules: Ensure termination, not infinite loops
- Performance: Large attribute spaces (10 attributes × 20 values) with sparse constraints
- Edge cases: Empty attributes, single-value attributes, no constraints
Common Mistakes
- Forgetting to index constraints: Checking all C constraints at every step wastes time
- Not deduplicating input values: Leads to apparent duplicates or incorrect counting
- Shallow copying assignments: Mutating shared dictionaries produces garbage output
- Ignoring impossibility: Looping forever or returning fewer profiles silently
- Checking constraints too early: A "must_pair" rule can't be evaluated until both attributes are assigned