KatInterview

Alternating Chain Assembly from Both Ends

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingsimulationtwo-pointersarrays

Last updated

Tests two-pointer simulation with alternating turns, conditional greedy selection rules, tie-breaking logic, and strict-increase constraints.

Problem Statement

You are given a row of planks, represented as an array of positive integers planks, where planks[i] is the length of the i-th plank. Two builders, Builder 1 and Builder 2, take turns pulling planks from this row to assemble a chain, with Builder 1 going first.

On every turn, the active builder may only take from one of the two ends of the remaining row — the leftmost or the rightmost plank.

The chain has one rule: each plank added must be strictly longer than the one placed just before it. The very first plank placed has no minimum requirement.

Selection Rules

Each builder follows a fixed decision procedure on their turn:

  1. Determine which ends are eligible: an end is eligible if its plank length is strictly greater than the length of the most recently placed plank.
  2. If both ends are eligible:
    • Builder 1 takes the shorter of the two eligible ends. On a tie, Builder 1 takes the left end.
    • Builder 2 takes the longer of the two eligible ends. On a tie, Builder 2 takes the right end.
  3. If exactly one end is eligible, the active builder must take that end regardless of identity.
  4. If neither end is eligible, or no planks remain, assembly halts immediately.

What to Return

Simulate the entire process and return a tuple (count_1, count_2, chain) where:

  • count_1 — total planks collected by Builder 1
  • count_2 — total planks collected by Builder 2
  • chain — the plank lengths in the order they were added to the chain

Constraints

  • 1 <= len(planks) <= 2 * 10^5
  • 1 <= planks[i] <= 10^9
  • Expected time complexity: O(n)
  • Expected auxiliary space complexity: O(n) for the output chain

Examples

Example 1

Input: assemble_plank_chain([3, 1, 5, 2, 4])

Output: [1, 1, [3, 4]]

Example 2

Input: assemble_plank_chain([2, 6, 3, 5, 4])

Output: [1, 1, [2, 6]]

Example 3

Input: assemble_plank_chain([5, 2, 5])

Output: [1, 0, [5]]

Hints

Hint 1

Track just four pieces of state as you iterate: a left pointer, a right pointer, the length of the last plank placed (start it at 0 so the first pick is always valid), and whose turn it is.

Hint 2

Separate the validity check from the preference logic. First figure out which ends are eligible, then — only if both are eligible — apply the builder's tie-breaking rule.

Hint 3

Builder 1 picks left when left_value <= right_value; Builder 2 picks left when left_value > right_value. When only one end is eligible, neither builder has a choice. The single-plank case (left == right) resolves correctly without special handling.