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-d buffer, a k-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

  1. 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 k houses 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 general
    

    The 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.

  2. 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 two O(n) chain passes; a tree needs an O(n) bottom-up traversal; an arbitrary network is NP-hard.
    Do conflicts span only immediate neighbors, distance d, or custom pairs? Distance d looks back to i - 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 [] yields 0. If at least one house is mandatory and all scores are negative (say [-9, -2, -6]), the answer is -2, not 0.
    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 requires O(n) stored decisions plus a deterministic tie rule.
    Is there an upper bound k on 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 n and values[i]? Governs runtime targets and integer width: n = 100,000 with scores up to 10^9 can reach 5 * 10^13, overflowing signed 32-bit integers (~2.1 * 10^9) and requiring 64-bit arithmetic.
  3. Declare the baseline model explicitly

    When constraints are intentionally left open, state your baseline model clearly before writing any recurrence:

    Illustrative baseline model: n houses sit along a single straight chain 0 .. n - 1 with values[i] >= 0. Immediate neighbors (i and i + 1) cannot both be chosen, selecting zero houses is valid (scoring 0), and we return only the maximum total score.

    Under this baseline, two naive strategies fail right away:

    • Exhaustive search (2^n subsets): enumerating subsets doubles with every house, exceeding one billion subsets by n = 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 takes 7 first, blocking both 6s for a total of 7, whereas indices 0 and 2 score 6 + 6 = 12.
  4. 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 i after processing 0 .. i - 1, only one prior detail affects legality: whether house i - 1 was taken. Decisions at i - 2 or earlier cannot conflict with i. Thus each prefix 0 .. i needs 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} -> 13
    

    Notice how the winning subset flips back and forth ({1} at i = 1, {0, 2} at i = 2, {1, 3} at i = 3, {0, 2, 4} at i = 4), ending at max(13, 10) = 13 (3 + 6 + 4).

  5. Write clean O(n) time, O(1) space code for the baseline chain

    Because step i reads only take[i - 1] and skip[i - 1], two scalar variables suffice. Compute new_take and new_skip from the previous step before reassigning take and skip:

    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_take and new_skip first prevents overwriting take prematurely (take = skip + value followed by skip = max(take, skip) would illegally allow adjacent picks). Empty input returns 0, [v] returns v, and [a, b] returns max(a, b) in O(n) time and O(1) space.

  6. Adapt the state when clarified constraints change

    Changing any answer from our discovery checklist modifies the algorithm predictably:

    • Closed ring (0 and n - 1 also conflict): no legal subset contains both 0 and n - 1. Every legal subset either omits n - 1 (living inside 0 .. n - 2) or omits 0 (living inside 1 .. n - 1). Run rob_line on both subranges and take the larger result (after handling n <= 1), keeping O(n) time and O(1) space.
    • Distance-d buffer (selecting i blocks i - d .. i - 1): track best[i] on prefix 0 .. i; taking i scores values[i] + best[i - d - 1] (0 when i - d - 1 < 0), while skipping i scores best[i - 1], in O(n) time.
    • At most k selections: include selection count c (0 <= c <= k) in the state (take[c], skip[c]), running in O(n * k) time and O(k) space. On [3, 8, 6, 2, 4], k = 1 gives 8 and k = 2 gives 12 (8 + 4).
    • Rooted tree (parent-child pairs conflict): propagate (take[node], skip[node]) bottom-up from leaves to the root in O(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.

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, two O(n) scans on a ring, and O(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 + value and new_skip = max(take, skip) in O(n) time and O(1) extra space.
  • Additional constraints extend the state systematically. Distance-d exclusions look back to i - d - 1 (O(n) time); a cap of k picks adds a count axis (O(n * k) time, O(k) space); reconstructing chosen slots requires O(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 than 0), deterministic tie rules for index output, and 64-bit integer accumulation when n * max_value exceeds 2^31 - 1.

Common mistakes

  • Guessing linear or circular topology without asking. Leaving layout implicit risks solving the wrong specification ([4, 5, 4] yields 8 on a chain vs. 5 on a ring).
  • Relying on greedy largest-first selection. Choosing 7 first on [6, 7, 6] blocks both 6s and scores 7 instead of 12.
  • Mutating take before computing skip. Writing take = skip + value followed by skip = max(take, skip) feeds the updated take into skip, allowing adjacent houses to be picked together. Always compute new_take and new_skip from the prior step first.
  • Returning take instead of max(take, skip). The optimal subset often skips the last slot—for instance, on [2, 9, 1], ending on take yields 3 (2 + 1) whereas skip yields 9.
  • Handling a ring by forcing slot 0 to be chosen. "Force slot 0 and forbid n - 1" misses optima that skip both endpoints. Instead, take the maximum of solving 0 .. n - 2 and solving 1 .. 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 0 and slot n - 1, so every valid subset either omits n - 1 (lying wholly inside 0 .. n - 2) or omits 0 (lying wholly inside 1 .. n - 1). Handle n == 0 (0) and n == 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 in O(n) time and O(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 full take[0..n-1] and skip[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 slot i when take[i] == skip[i]). After filling take and skip forward, walk backward from n - 1 down to 0: whenever slot i + 1 was not selected and take[i] > skip[i], append i and mark i - 1 as 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 strict take[i] > skip[i] at i = 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

Similar questions

More Digitalocean interview questions

All 3 Digitalocean questions →