Clarifying Conflict Constraints in House-Selection Optimization
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Prompt
You are presented with an intentionally open-ended discrete optimization scenario: every house carries a numeric payoff, certain combinations of houses are mutually incompatible, and you want to select a valid subset with the largest combined payoff. Walk through every ambiguity you need to settle with the interviewer before committing to an algorithm, explain how different answers change the computational difficulty and state representation, and work out one explicitly labeled baseline formulation (for instance, a straight one-dimensional block of non-negative payoffs where side-by-side neighbors exclude one another) without silently assuming a ring-shaped street or any unstated variant.
Scope & Expectations
- Constraint discovery: Identify the open dimensions—topology (chain, closed loop, rooted hierarchy, or general network), exclusion distance or custom conflict pairs, payoff domain (zeros, negatives, whether choosing zero houses is valid, integer overflow bounds), selection count limits, and output contract (maximum scalar total vs. chosen positions with deterministic tie-breaking).
- Explicit baseline formulation: Declare your baseline model assumptions clearly before deriving an
O(n)-time,O(1)-space dynamic program over prefix states. - Algorithmic impact of rule changes: Show concretely how switching to a closed loop, a distance-
dbuffer, ak-pick cap, a tree hierarchy, or an arbitrary exclusion network reshapes the recurrence or pushes the problem into NP-hard territory.
Step-by-step walkthrough
Separate what is given from what is still unknown
Only the high-level problem family is given: each house carries a numeric score, certain combinations cannot be picked together, and we want a conflict-free subset maximizing total score. Every structural rule that dictates the algorithm remains open:
- Topology and exclusion rules: which houses block which other houses. Model this as a conflict graph (a network with one vertex per house and an edge joining any pair of houses that cannot both be selected). Choosing the highest-scoring legal subset is then maximum-weight independent set (finding a subset of vertices of maximum total weight with no edge connecting any two chosen vertices).
- Score domain: whether scores are guaranteed non-negative (
>= 0) or can be negative, whether they are integers or floats, and their maximum magnitude. - Return contract: whether the caller wants only the optimal scalar sum, the list of selected indices, or both, plus how ties between equal-scoring subsets should be broken.
- Cardinality rules: whether selecting zero houses is permitted, at least one house is mandatory, or at most
khouses may be chosen.
Straight chain Closed ring Rooted hierarchy Arbitrary conflict graph [0]--[1]--[2]--[3] [0]--[1] parent [0] [0]---[1] | | / \ | \ / | [3]--[2] [1] [2] [3]---[2] O(n) single pass Two O(n) passes O(n) bottom-up NP-hard in generalThe conflict graph's shape matters above everything else because it shifts the exact same word problem between linear time (
O(n)) and NP-hard (problems with no known polynomial-time exact algorithm across all inputs). Pin down these rules before writing code, and never assume a closed loop merely because a familiar follow-up uses one.Ask the clarifying questions that change the algorithm
Pair each clarifying question with the concrete algorithmic consequence of its answer:
Clarifying question How the answer changes the algorithm What is the conflict topology: a straight chain, closed ring, rooted tree, or arbitrary network? A chain needs one O(n)pass; a ring needs twoO(n)chain passes; a tree needs anO(n)bottom-up traversal; an arbitrary network is NP-hard.Do conflicts span only immediate neighbors, distance d, or custom pairs?Distance dlooks back toi - d - 1; custom exclusion pairs induce a general conflict graph.Can scores be zero or negative, and is an empty selection valid? When choosing nothing is valid, negative houses are skipped and []yields0. If at least one house is mandatory and all scores are negative (say[-9, -2, -6]), the answer is-2, not0.Should we return only the best score or the selected positions, and how do ties break? Returning the score alone uses O(1)extra space on a chain; reconstructing positions requiresO(n)stored decisions plus a deterministic tie rule.Is there an upper bound kon the number of selected houses?Adds a count dimension to the DP state, increasing runtime to O(n * k).What are the upper bounds on nandvalues[i]?Governs runtime targets and integer width: n = 100,000with scores up to10^9can reach5 * 10^13, overflowing signed 32-bit integers (~2.1 * 10^9) and requiring 64-bit arithmetic.Declare the baseline model explicitly
When constraints are intentionally left open, state your baseline model clearly before writing any recurrence:
Illustrative baseline model:
nhouses sit along a single straight chain0 .. n - 1withvalues[i] >= 0. Immediate neighbors (iandi + 1) cannot both be chosen, selecting zero houses is valid (scoring0), and we return only the maximum total score.Under this baseline, two naive strategies fail right away:
- Exhaustive search (
2^nsubsets): enumerating subsets doubles with every house, exceeding one billion subsets byn = 30. - Greedy largest-first: repeatedly grabbing the highest-scoring available house fails whenever one slightly bigger middle house blocks two lucrative neighbors. On
values = [6, 7, 6], greedy takes7first, blocking both6s for a total of7, whereas indices0and2score6 + 6 = 12.
- Exhaustive search (
Derive the linear dynamic program from the previous slot
We solve the chain cleanly with dynamic programming (DP) (solving sequential prefixes while retaining only the summary of earlier choices that future legality depends on).
When deciding on house
iafter processing0 .. i - 1, only one prior detail affects legality: whether housei - 1was taken. Decisions ati - 2or earlier cannot conflict withi. Thus each prefix0 .. ineeds just two numbers:take[i] = best valid score from houses 0..i when house i IS selected skip[i] = best valid score from houses 0..i when house i is NOT selected Recurrence at house i (from virtual base take[-1] = 0, skip[-1] = 0): take[i] = skip[i - 1] + values[i] (taking house i requires skipping house i - 1) skip[i] = max(take[i - 1], skip[i - 1]) (skipping house i leaves house i - 1 unrestricted) Optimal total = max(take[n - 1], skip[n - 1])Trace this recurrence on
values = [3, 8, 6, 2, 4]:i values[i] take[i] = skip[i-1] + values[i] skip[i] = max(take[i-1], skip[i-1]) best subset so far - --------- ------------------------------- ----------------------------------- ------------------ 0 3 0 + 3 = 3 max(0, 0) = 0 {0} -> 3 1 8 0 + 8 = 8 max(3, 0) = 3 {1} -> 8 2 6 3 + 6 = 9 max(8, 3) = 8 {0, 2} -> 9 3 2 8 + 2 = 10 max(9, 8) = 9 {1, 3} -> 10 4 4 9 + 4 = 13 max(10, 9) = 10 {0, 2, 4} -> 13Notice how the winning subset flips back and forth (
{1}ati = 1,{0, 2}ati = 2,{1, 3}ati = 3,{0, 2, 4}ati = 4), ending atmax(13, 10) = 13(3 + 6 + 4).Write clean O(n) time, O(1) space code for the baseline chain
Because step
ireads onlytake[i - 1]andskip[i - 1], two scalar variables suffice. Computenew_takeandnew_skipfrom the previous step before reassigningtakeandskip:def rob_line(values): """Return the maximum total from a straight chain where adjacent houses conflict.""" # Running prefix optima: # take = best total including the previous house # skip = best total excluding the previous house take = 0 skip = 0 for value in values: new_take = skip + value new_skip = max(take, skip) take = new_take skip = new_skip return max(take, skip) print(rob_line([3, 8, 6, 2, 4])) # 13 (houses 0, 2, 4) print(rob_line([6, 7, 6])) # 12 (houses 0, 2) print(rob_line([])) # 0 (empty block)Computing
new_takeandnew_skipfirst prevents overwritingtakeprematurely (take = skip + valuefollowed byskip = max(take, skip)would illegally allow adjacent picks). Empty input returns0,[v]returnsv, and[a, b]returnsmax(a, b)inO(n)time andO(1)space.Adapt the state when clarified constraints change
Changing any answer from our discovery checklist modifies the algorithm predictably:
- Closed ring (
0andn - 1also conflict): no legal subset contains both0andn - 1. Every legal subset either omitsn - 1(living inside0 .. n - 2) or omits0(living inside1 .. n - 1). Runrob_lineon both subranges and take the larger result (after handlingn <= 1), keepingO(n)time andO(1)space. - Distance-
dbuffer (selectingiblocksi - d .. i - 1): trackbest[i]on prefix0 .. i; takingiscoresvalues[i] + best[i - d - 1](0wheni - d - 1 < 0), while skippingiscoresbest[i - 1], inO(n)time. - At most
kselections: include selection countc(0 <= c <= k) in the state (take[c],skip[c]), running inO(n * k)time andO(k)space. On[3, 8, 6, 2, 4],k = 1gives8andk = 2gives12(8 + 4). - Rooted tree (parent-child pairs conflict): propagate
(take[node], skip[node])bottom-up from leaves to the root inO(n)time:
[0] (val=4) / \ (5) [1] [2] (6) Optimal independent sets of score 11: / \ \ - Choose {1, 2}: 5 + 6 = 11 (2) [3] [4] [5] (1) - Choose {2, 3, 4}: 6 + 2 + 3 = 11 (3)def rob_tree(values, children, root=0): """Return the maximum total on a rooted tree where parent-child pairs conflict.""" # Record a top-down BFS order so reversing it visits every child before its parent order = [root] idx = 0 while idx < len(order): node = order[idx] for child in children[node]: order.append(child) idx += 1 take = [0] * len(values) skip = [0] * len(values) for node in reversed(order): take[node] = values[node] for child in children[node]: take[node] += skip[child] skip[node] += max(take[child], skip[child]) return max(take[root], skip[root]) print(rob_tree([4, 5, 6, 2, 3, 1], [[1, 2], [3, 4], [5], [], [], []])) # 11- General exclusion graph: arbitrary long-range edges destroy bounded prefix memory. Because maximum-weight independent set is NP-hard on general graphs, match the solver to graph structure: exact branch-and-bound (backtracking search that prunes branches whose optimistic upper bound cannot beat the best score found) or integer linear programming for small
n; polynomial min-cut reduction when the conflict graph is bipartite (two-colorable with conflicts only across sides); or greedy/local-search approximations at large scale.
- Closed ring (
Intuition & how it works
Imagine planning which café kiosks to open along a commercial district when franchise exclusivity rules forbid opening conflicting locations, and each lot has an estimated profit. Before writing a formula, you must inspect the district map: do the lots line up along one straight avenue, wrap around a circular roundabout, branch through floors of a mall directory, or follow custom pairwise contracts? Once you confirm they sit along one straight avenue where only immediate next-door lots conflict, walking down the block requires just two sticky notes from the lot you just passed: the best total profit if you opened that lot (take), and the best total profit if you skipped it (skip).
Jumping straight into brute force or greedy rules fails immediately. Testing all 2^n subsets passes a billion checks at n = 30, while greedily picking the largest lot first gets trapped whenever one slightly higher-scoring middle lot blocks two strong neighbors—on [6, 7, 6], grabbing 7 blocks both 6s for 7 instead of 6 + 6 = 12. Coding before clarifying topology is just as risky: [4, 5, 4] scores 8 (4 + 4) on a straight block, yet drops to 5 on a closed loop where the ends touch.
Trace the two sticky notes along a 4-lot straight block values = [3, 8, 6, 2] starting from take = 0, skip = 0:
1. Lot 0 (3): taking gives 0 + 3 = 3; skipping gives max(0, 0) = 0 (take = 3, skip = 0).
2. Lot 1 (8): taking requires skipping lot 0, giving 0 + 8 = 8; skipping keeps max(3, 0) = 3 (take = 8, skip = 3).
3. Lot 2 (6): taking adds 6 to lot 1's skip (3 + 6 = 9); skipping keeps max(8, 3) = 8 (take = 9, skip = 8).
4. Lot 3 (2): taking adds 2 to lot 2's skip (8 + 2 = 10); skipping keeps max(9, 8) = 9 (take = 10, skip = 9).
The optimal total is max(10, 9) = 10 (lots 1 and 3), computed in a single left-to-right scan.
Key points
- Pin down the conflict graph before picking a technique. Treating houses as vertices and forbidden pairs as edges defines a conflict graph (a network encoding pairwise exclusions), casting the problem as maximum-weight independent set (finding the highest-weight subset of mutually non-adjacent vertices). Complexity ranges from
O(n)on a chain, twoO(n)scans on a ring, andO(n)bottom-up on a tree to NP-hard (no known polynomial-time exact solver for all inputs) on general networks. - State your baseline assumptions out loud. Declaring "straight chain, non-negative scores, immediate neighbors conflict, empty subset valid, return scalar maximum" grounds every complexity and boundary claim.
- Dynamic programming (DP) retains only decision-relevant history. Dynamic programming solves sequential subproblems by storing only the summary of past choices that constrains future steps. Under neighbor exclusions on a chain, future legality depends exclusively on whether the prior slot was chosen:
new_take = skip + valueandnew_skip = max(take, skip)inO(n)time andO(1)extra space. - Additional constraints extend the state systematically. Distance-
dexclusions look back toi - d - 1(O(n)time); a cap ofkpicks adds a count axis (O(n * k)time,O(k)space); reconstructing chosen slots requiresO(n)memory for back-pointers (recorded per-step choices used to retrace the winning subset). - Verify numeric and boundary contracts. Clarify empty input (
0), single-house input, all-negative arrays when at least one pick is mandatory (max(values)rather than0), deterministic tie rules for index output, and 64-bit integer accumulation whenn * max_valueexceeds2^31 - 1.
Common mistakes
- Guessing linear or circular topology without asking. Leaving layout implicit risks solving the wrong specification (
[4, 5, 4]yields8on a chain vs.5on a ring). - Relying on greedy largest-first selection. Choosing
7first on[6, 7, 6]blocks both6s and scores7instead of12. - Mutating
takebefore computingskip. Writingtake = skip + valuefollowed byskip = max(take, skip)feeds the updatedtakeintoskip, allowing adjacent houses to be picked together. Always computenew_takeandnew_skipfrom the prior step first. - Returning
takeinstead ofmax(take, skip). The optimal subset often skips the last slot—for instance, on[2, 9, 1], ending ontakeyields3(2 + 1) whereasskipyields9. - Handling a ring by forcing slot
0to be chosen. "Force slot0and forbidn - 1" misses optima that skip both endpoints. Instead, take the maximum of solving0 .. n - 2and solving1 .. n - 1. - Applying the two-scalar chain recurrence to arbitrary exclusion pairs. Once distant slots can conflict arbitrarily, tracking only the previous slot cannot prevent illegal combinations.
Follow-up questions
- How does your one-dimensional recurrence change if the endpoints of the street also conflict with each other? No valid subset may contain both slot
0and slotn - 1, so every valid subset either omitsn - 1(lying wholly inside0 .. n - 2) or omits0(lying wholly inside1 .. n - 1). Handlen == 0(0) andn == 1(values[0], confirming a single house does not exclude itself), run the chain DP over both index ranges without slicing copies, and return their maximum inO(n)time andO(1)extra space—for example, on[4, 5, 4],max(rob_line([4, 5]), rob_line([5, 4])) = max(5, 5) = 5.
def rob_line_range(values, start, end):
"""Run the chain DP across values[start:end] in O(1) space."""
take = 0
skip = 0
for i in range(start, end):
new_take = skip + values[i]
new_skip = max(take, skip)
take = new_take
skip = new_skip
return max(take, skip)
def rob_circle(values):
"""Maximum score when houses form a closed ring (0 and n-1 also conflict)."""
n = len(values)
if n == 0:
return 0
if n == 1:
return values[0]
without_last = rob_line_range(values, 0, n - 1)
without_first = rob_line_range(values, 1, n)
return max(without_last, without_first)
- What extra state and tie-breaking rules must you add when the caller wants the selected house positions rather than just the optimal score? You must retain
O(n)history—such as the fulltake[0..n-1]andskip[0..n-1]arrays (or one boolean decision per slot)—and establish a deterministic tie-breaking rule whenever multiple valid subsets tie for the best score (for instance, preferring to skip slotiwhentake[i] == skip[i]). After fillingtakeandskipforward, walk backward fromn - 1down to0: whenever sloti + 1was not selected andtake[i] > skip[i], appendiand marki - 1as blocked; reversing the collected list yields[0, 2, 4]on[3, 8, 6, 2, 4]and[]or[0]consistently on ties like[5, 5]([0]under stricttake[i] > skip[i]ati = 0).
def rob_line_with_indices(values):
"""Return (max_total, chosen_indices); ties at slot i prefer skipping slot i."""
n = len(values)
if n == 0:
return 0, []
take = [0] * n
skip = [0] * n
for i in range(n):
prev_take = take[i - 1] if i > 0 else 0
prev_skip = skip[i - 1] if i > 0 else 0
take[i] = prev_skip + values[i]
skip[i] = max(prev_take, prev_skip)
chosen = []
must_skip = False # True immediately after selecting slot i + 1
for i in range(n - 1, -1, -1):
if not must_skip and take[i] > skip[i]:
chosen.append(i)
must_skip = True
else:
must_skip = False
chosen.reverse()
return max(take[-1], skip[-1]), chosen
Follow-up questions
- How does your one-dimensional recurrence change if the endpoints of the street also conflict with each other?
- What extra state and tie-breaking rules must you add when the caller wants the selected house positions rather than just the optimal score?
Similar questions
- Longest Uniform Substring Under Bounded Character Edits
- Multi-Tenant Ad Serving and Attribution Platform
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging