{"id":"container-with-most-water","title":"Container With Most Water","difficulty":"medium","patterns":["two-pointers"],"primaryConcept":"array-two-pointers-scan","concepts":["array-two-pointers-scan"],"problemForm":"core","companies":[],"category":"arrays-strings","compareMode":"exact","description":"Given an integer array `height`, choose two indices `i` and `j` to form a container with the x-axis. The container width is `j - i`, and its height is the smaller of `height[i]` and `height[j]`.\n\nReturn the maximum amount of water any such container can hold.\n\nRequirements:\n- You must choose two different indices.\n- Return the maximum area as an integer.\n- The order of heights cannot be changed.","examples":[{"input":"height = [1,8,6,2,5,4,8,3,7]","output":"49","explanation":"The best container uses heights 8 and 7 at indices 1 and 8, giving width 7 and area 7 * 7 = 49."},{"input":"height = [1,1]","output":"1","explanation":"The only possible container has width 1 and height 1."},{"input":"height = [4,3,2,1,4]","output":"16","explanation":"The two endpoints form area 4 * 4 = 16."}],"constraints":[{"id":"2-len-height-10-5","text":"2 <= len(height) <= 10^5","check":{"kind":"sizeRange","target":"height","measure":"arrayLength","min":2,"max":100000}},{"id":"0-height-i-10-4","text":"0 <= height[i] <= 10^4","check":{"kind":"valueRange","target":"height","selector":"arrayItems","min":0,"max":10000}}],"starterCode":"class Solution:\n    def maxArea(self, height: list[int]) -> int:\n        # Your code here\n        pass","functionName":"maxArea","testCases":[{"id":"1","input":{"height":[1,8,6,2,5,4,8,3,7]},"expected":49,"description":"Canonical wide optimal container."},{"id":"2","input":{"height":[1,1]},"expected":1,"description":"Smallest allowed input."},{"id":"3","input":{"height":[4,3,2,1,4]},"expected":16,"description":"Best container uses endpoints."},{"id":"4","input":{"height":[1,2,1]},"expected":2,"description":"Best area is not from tallest duplicated height."},{"id":"5","input":{"height":[2,3,10,5,7,8,9]},"expected":36,"description":"Interior tall bars with wider tradeoff."},{"id":"h1","input":{"height":[0,2,0,2]},"expected":4,"description":"Zeros between equal bars still allow a nonzero container."},{"id":"h2","input":{"height":[2,3,4,5,18,17,6]},"expected":17,"description":"The tallest pair is too close together to win."},{"id":"h3","input":{"height":[5,5,5,5]},"expected":15,"description":"Uniform heights make the widest span optimal."},{"id":"h4","input":{"height":[6,1,1,1,6]},"expected":24,"description":"Tall endpoints beat all narrow interior choices."},{"id":"h5","input":{"height":[0,0,0,0]},"expected":0,"description":"All zero heights produce no water."},{"id":"h6","input":{"height":[1,2]},"expected":1,"description":"The minimum valid array length has only one possible container."},{"id":"h7","input":{"height":[1,100,1,1,100,1]},"expected":300,"description":"Tall interior walls can beat every endpoint pairing."}],"hints":[{"level":1,"content":"Area depends on width and the shorter of the two chosen heights. Which pointer is limiting the current container?","revealPattern":false},{"level":2,"content":"Start with the widest container, then move the pointer at the shorter height inward.","revealPattern":true},{"level":3,"content":"Moving the taller side cannot increase height enough to compensate for lost width, because the shorter side still limits the container.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"all-pairs","name":"All pairs","summary":"Compute every possible container.","decisionReason":"It measures every pair of walls, which is the square of their number, when most pairs can never be the best.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["Runs in O(n^2) time and uses O(1) space."],"isOptimal":false},{"id":"two-pointers","name":"Move the shorter wall","summary":"Start at both ends, update max area, and move the pointer with the smaller height.","decisionReason":"Start at the widest pair and walk inward, always moving the shorter wall, so each step has a chance to improve and the whole thing is one pass.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["Runs in O(n) time and uses O(1) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-pointers","title":"Initialize opposite pointers","description":"Place one pointer at each end of the array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"initializes_boundary_pointers","scope":"init-pointers","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Starting both pointers at the same side","Starting the right pointer at len(height) instead of len(height) - 1"],"hint":"The widest possible container is the first candidate.","semanticSpec":{"intent":"Initialize opposite boundary pointers so the first candidate uses the widest possible container.","doneWhen":"This step is done when one pointer starts at index 0 and the other starts at the last index before the inward scan begins.","shouldFailWhen":"This step should fail if both pointers start on the same side, if the right pointer is not tied to the end of the array, or if the algorithm starts with a narrowed window.","roles":["left pointer","right pointer","height array","widest candidate"],"mustProve":["The left boundary starts at the first index.","The right boundary starts at the last valid index.","The pointers are initialized before the convergence loop."],"mustNotAccept":["Starting right at `len(height)`.","Starting from arbitrary interior positions.","Using nested all-pairs loops instead of boundary pointers."],"equivalentVariants":["Use `left = 0` and `right = len(height) - 1`.","Use equivalent pointer variables seeded to the two ends of the height array."],"proofSnippets":[{"id":"py-container-init-pointers","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    while left < right:\n        return 0\n    return 0"}]}},{"id":"compute-area","title":"Compute current area","description":"At each step, compute width times the shorter boundary height.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"computes_boundary_width_extremum_contribution","scope":"compute-area","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Using the taller height","Forgetting width is right - left"],"hint":"Water can only rise to the shorter wall.","semanticSpec":{"intent":"Compute the area for the current pair from the pointer distance and the shorter boundary height.","doneWhen":"This step is done when each loop iteration derives width from the two pointers, derives height from the smaller boundary value, and forms their product.","shouldFailWhen":"This step should fail if the code uses the taller boundary as the water height, forgets the width, uses adjacent distance only, or computes area after moving a pointer without checking the current pair.","roles":["left pointer","right pointer","width","shorter boundary height","current area"],"mustProve":["Width is derived from the distance between the two current pointers.","Container height is derived from the minimum of the two boundary heights.","The current area is width multiplied by that limiting height."],"mustNotAccept":["Using `max(height[left], height[right])` for the water height.","Using only height and ignoring width.","Computing area from non-boundary values."],"equivalentVariants":["Use `width = right - left` and `area = width * min(height[left], height[right])`.","Use equivalent inline arithmetic that preserves the same width and limiting-height semantics."],"neededLowerLayerFact":{"suggestedFamily":"two-pointer","suggestedFact":"computes_boundary_width_extremum_area","suggestedScope":"compute-area","owner":"Layer 5A structural fact plus Layer 6 familyFact reader"},"proofSnippets":[{"id":"py-container-compute-area","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    while left < right:\n        width = right - left\n        area = width * min(height[left], height[right])\n        return area\n    return 0"}]}},{"id":"update-best","title":"Track maximum area","description":"Update the best area after evaluating each pointer pair.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"updates_boundary_accumulation_extremum","scope":"update-best","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving pointers before checking area","Returning only the last area"],"hint":"Record the best area seen so far.","semanticSpec":{"intent":"Maintain a best-area accumulator for the maximum container area seen so far.","doneWhen":"This step is done when a numeric best state is initialized before the loop and updated from current candidate areas during the scan.","shouldFailWhen":"This step should fail if no best state exists, if the result returns only the last area, or if the update is not tied to the boundary scan.","roles":["best area","current area","boundary scan","numeric accumulator"],"mustProve":["A numeric result state is initialized before the scan.","The scan updates that state from candidate boundary contributions.","The result state is separate from the pointer variables."],"mustNotAccept":["Returning the final current area only.","Using a pointer as the best-area accumulator.","Updating best before computing any candidate contribution."],"equivalentVariants":["Use `best = max(best, area)`.","Use an equivalent conditional update when the current area exceeds the best area."],"semanticFactNote":"This existing fact proves boundary accumulation state, but a later directional-area fact should make the current-area coupling more precise.","neededLowerLayerFact":{"suggestedFamily":"two-pointer","suggestedFact":"updates_best_from_boundary_area","suggestedScope":"update-best","owner":"Layer 5A numeric extremum/update relation plus Layer 6 two-pointer fact reader"},"proofSnippets":[{"id":"py-container-update-best","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    max_area = 0\n    while left < right:\n        width = right - left\n        area = width * min(height[left], height[right])\n        max_area = max(max_area, area)\n        return 0\n    return 0"}]}},{"id":"move-shorter","title":"Move the limiting side","description":"Move the pointer at the shorter height inward.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"moves_smaller_boundary_inward","scope":"move-shorter","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving the taller side and keeping the same limiter","Moving both pointers every time"],"hint":"Only moving the shorter side can reveal a taller limiting wall.","semanticSpec":{"intent":"Move inward from the shorter boundary because that side limits the current container height.","doneWhen":"This step is done when the loop compares the two boundary heights and advances the pointer on the smaller side inward.","shouldFailWhen":"This step should fail if the taller side is always moved, both pointers move unconditionally, or movement is unrelated to the boundary-height comparison.","roles":["left boundary height","right boundary height","limiting side","inward pointer movement"],"mustProve":["The branch compares the current left and right boundary heights.","The selected movement is based on the smaller limiting boundary.","Pointer movement keeps the scan converging inward."],"mustNotAccept":["Moving both pointers every iteration.","Moving the taller boundary because it is taller.","Changing pointers without comparing boundary heights."],"equivalentVariants":["Use `if height[left] < height[right]: left += 1 else: right -= 1`.","Use the symmetric comparison with equivalent shorter-side movement."],"neededLowerLayerFact":{"suggestedFamily":"two-pointer","suggestedFact":"advances_shorter_boundary_pointer","suggestedScope":"move-shorter","owner":"Layer 5A pointer movement relation plus Layer 6 two-pointer fact reader"},"proofSnippets":[{"id":"py-container-move-shorter","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    max_area = 0\n    while left < right:\n        width = right - left\n        area = width * min(height[left], height[right])\n        max_area = max(max_area, area)\n        if height[left] < height[right]:\n            left += 1\n        else:\n            right -= 1\n    return 0"}]}},{"id":"return-best","title":"Return the best area","description":"Return the maximum area found after the two pointers finish converging.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"returns_boundary_accumulation_result","scope":"return-best","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Returning the last computed area instead of the best one","Returning a pointer index instead of the area"],"hint":"Return the tracked maximum after the pointers meet.","semanticSpec":{"intent":"Return the maximum container area tracked during the boundary-converging scan.","doneWhen":"This step is done when the function returns the best area state after the pointer loop completes.","shouldFailWhen":"This step should fail if the code returns the last area, a pointer, or an uninitialized value.","roles":["best area","terminal return","two-pointer scan"],"mustProve":["A best-area state is tracked during the scan.","The returned value is that best-area state after convergence."],"mustNotAccept":["Returning the current area from only the final pointer position.","Returning left or right pointer indices."],"equivalentVariants":["Return max_area after the loop.","Return an equivalent best-area accumulator."],"proofSnippets":[{"id":"py-container-return-best","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    max_area = 0\n    while left < right:\n        area = (right - left) * min(height[left], height[right])\n        max_area = max(max_area, area)\n        if height[left] < height[right]:\n            left += 1\n        else:\n            right -= 1\n    return max_area"}]}}],"version":2,"slides":[{"id":"read-the-signal","chapter":"The walls","kind":"info","eyebrow":"Read the problem","title":"Hold the most water between two walls","workspacePanel":"problem","body":["You get heights for a row of walls. Pick two of them to form a container. The water it holds is the shorter wall (the water spills over the lower side) times the distance between them.","Two things fight each other: width wants the walls far apart, height wants them tall. The obvious approach measures every pair. Watch what that costs."]},{"id":"brute-force","chapter":"The obvious way","kind":"code-trace","eyebrow":"The obvious way","title":"Measure every pair of walls","summary":"Measuring every pair finds the most water, but the number of pairs grows fast. Watch how many measurements that takes as the walls multiply.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"best = 0\nfor left in range(len(height)):\n    for right in range(left + 1, len(height)):\n        area = min(height[left], height[right]) * (right - left)\n        if area > best:\n            best = area\nreturn best","steps":[{"id":"left-zero","title":"Pair wall 0 with every other","codeLine":4,"summary":"Wall 0 has height 1, so every pair using it holds at most width times 1. All of those measurements are weak, yet each is computed.","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":0,"right":8,"labels":{"nums":"height"}}},{"id":"left-one","title":"Then pair wall 1 with every other","codeLine":2,"summary":"Wall 1 is height 8. It pairs with walls 2 through 8 in turn, re-reading every later wall the previous round already visited.","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":1,"right":8,"labels":{"nums":"height"}}},{"id":"all-pairs","title":"Every wall pairs with every later wall","codeLine":3,"summary":"The work grows with the square of the number of walls, even though most pairs, like anything anchored to the height-1 wall, can never win.","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":2,"right":6,"labels":{"nums":"height"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let best = 0;\nfor (let left = 0; left < height.length; left++) {\n    for (let right = (left + 1); right < height.length; right++) {\n        const area = Math.min(height[left], height[right]) * (right - left);\n        if (area > best) {\n            best = area;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let best = 0;\nfor (let left = 0; left < height.length; left++) {\n    for (let right = (left + 1); right < height.length; right++) {\n        const area = Math.min(height[left], height[right]) * (right - left);\n        if (area > best) {\n            best = area;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int best = 0;\nfor (int left = 0; left < height.size(); left++) {\n    for (int right = (left + 1); right < height.size(); right++) {\n        int area = Math.min(height.get(left), height.get(right)) * (right - left);\n        if (area > best) {\n            best = area;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int best = 0;\nfor (int left = 0; left < height.Count; left++) {\n    for (int right = left + 1; right < height.Count; right++) {\n        int area = Math.Min(height[left], height[right]) * (right - left);\n        if (area > best) {\n            best = area;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int best = 0;\nfor (int left = 0; left < height.size(); left++) {\n    for (int right = (left + 1); right < height.size(); right++) {\n        int area = min(height[left], height[right]) * (right - left);\n        if (area > best) {\n            best = area;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}}}},"body":["An outer loop fixes the left wall; an inner loop pairs it with every wall to its right."]},{"id":"brute-force-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Count the work","title":"How many pairs do the nested loops measure on 100,000 walls?","summary":"The inner loop reruns for every wall the outer loop fixes.","workspacePanel":"trace","options":[{"id":"all-pairs","label":"About 100,000 times 100,000, the square of the wall count","rationale":"Every wall pairs with every later wall, so the measurements grow as the square of the count, about five billion for 100,000 walls. That is the cost to beat.","isCorrect":true},{"id":"one-pass","label":"About 100,000, one measurement per wall","rationale":"That is a single pass, but the inner loop runs again for each wall the outer loop fixes, so the total is the square, not one per wall.","isCorrect":false},{"id":"log-pairs","label":"About 100,000 times 17, halving the range each round","rationale":"Nothing is halved here. Both loops walk the full array, so the work is the square of the count, not n times log n.","isCorrect":false}],"answer":"About the square of the wall count. The answer could be any pair, including the two ends, so the loops test almost all of them, roughly five billion measurements on 100,000 walls."},{"id":"start-wide","chapter":"The idea","kind":"case-probe","eyebrow":"Find the start","title":"Which single pair is guaranteed to have the most width?","summary":"Width is the distance between the two chosen walls.","workspacePanel":"visualizer","options":[{"id":"far-ends","label":"The two outermost walls","rationale":"No pair is wider than the full span. Starting there fixes width at its maximum, so from then on the only way to improve is taller walls.","isCorrect":true},{"id":"two-tallest","label":"The two tallest walls","rationale":"Tall walls help, but if they sit close together the width is tiny. The widest start is the outer ends, whatever their height.","isCorrect":false},{"id":"adjacent","label":"Two walls next to each other","rationale":"Neighbours give width 1, the smallest possible, so they throw away almost all of the available span.","isCorrect":false}],"answer":"The two ends. They give the largest possible width, so beginning there means every later move trades some width for a shot at more height.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start-wide-state","state":{"nums":[1,8,6,2,5,4,8,3,7],"labels":{"nums":"height"}}}]}},{"id":"which-to-move","chapter":"The idea","kind":"case-probe","eyebrow":"Find the move","title":"The two walls differ in height. Which one do you move inward?","summary":"The left wall is height 1, the right wall is height 7.","workspacePanel":"visualizer","options":[{"id":"shorter","label":"The shorter wall","rationale":"The shorter wall caps the water. Keeping it and moving the taller one only loses width, never gains height. Replacing the shorter wall is the only move that can help.","isCorrect":true},{"id":"taller","label":"The taller wall","rationale":"The water is already limited by the shorter wall, so a different taller wall changes nothing about the cap, and the container only gets narrower.","isCorrect":false},{"id":"either","label":"Either, it does not matter","rationale":"It does matter. Moving the taller wall can never improve a container the shorter wall already limits; moving the shorter one might.","isCorrect":false}],"answer":"The shorter wall. It is the one capping the water, so moving it is the only change that can raise the limit. Moving the taller wall just narrows the container.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"which-move-state","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":0,"right":8,"best":8,"labels":{"nums":"height"}}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":0,"right":8,"best":0,"labels":{"nums":"height"}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Start wide, walk the shorter wall in","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":0,"right":8,"best":0,"labels":{"nums":"height"}}}]},"body":["left and right start at the two ends, the widest container. best holds the most water found.","Each step measures min(height[left], height[right]) times the gap, raises best if it wins, then moves the shorter wall inward.","The pointers march toward each other, so the whole sweep is one pass from the outside in."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the walls","title":"Trace the closing walls","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-area","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":0,"right":8,"best":8,"labels":{"nums":"height"}}},{"id":"best-area","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":1,"right":8,"best":49,"labels":{"nums":"height"}}},{"id":"closing","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":1,"right":7,"best":49,"labels":{"nums":"height"}}}]},"beats":[{"id":"first-area","title":"Walls 0 (height 1) and 8 (height 7), width 8. Which wall moves?","summary":"The area here is min(1, 7) times 8 = 8, so best becomes 8.","prompt":"left holds height 1, right holds height 7.","options":[{"id":"move-left","label":"Move left inward","rationale":"The height-1 wall caps the water at 8. It can only get better by replacing that wall, so left moves in and right stays.","isCorrect":true},{"id":"move-right","label":"Move right inward","rationale":"The right wall is the taller one. Moving it keeps the height-1 cap and shrinks the width, so it cannot improve.","isCorrect":false},{"id":"stop","label":"Stop, this is the widest","rationale":"Widest is not most water; the height-1 wall is wasting it. Moving the shorter wall in can find a far better container.","isCorrect":false}],"answer":"Move left. The shorter wall caps the area at 8, so replacing it is the only hope of more. left advances to wall 1."},{"id":"best-area","title":"Now walls 1 (height 8) and 8 (height 7), width 7. What is the area?","summary":"best is 8 going in.","prompt":"The two walls are heights 8 and 7.","options":[{"id":"fortynine","label":"49, a new best","rationale":"min(8, 7) times 7 = 49, far above the old best of 8, so best jumps to 49.","isCorrect":true},{"id":"fiftysix","label":"56","rationale":"That would use height 8 for both walls, but the right wall is only 7. Water is capped by the shorter side, so it is 7 times 7.","isCorrect":false},{"id":"fortytwo","label":"42","rationale":"The width here is 7 (from index 1 to 8), not 6. min(8, 7) times 7 = 49.","isCorrect":false}],"answer":"49. min(8, 7) times the width 7 is 49, which beats 8, so best becomes 49."},{"id":"closing","title":"The walls keep closing in. Can any later pair beat 49?","summary":"From here the width only shrinks as the pointers approach.","prompt":"best is 49 and the container is narrowing.","options":[{"id":"no","label":"No, 49 stands as the answer","rationale":"Every remaining pair is narrower, and none has tall enough walls to make up for it, so best holds at 49 to the end.","isCorrect":true},{"id":"maybe-wider","label":"Yes, by widening again","rationale":"The pointers only move inward, so width never grows again. A later pair would need impossibly tall walls to beat 49.","isCorrect":false},{"id":"restart","label":"Only if the pointers reset","rationale":"They never reset; the sweep is one pass inward. 49 is the most water any pair holds.","isCorrect":false}],"answer":"No. The container only narrows from here and no remaining pair beats 49, so it is the answer."}]},{"id":"move-taller-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can you move a pointer first and measure the new pair?","summary":"Folding the move to the top of the loop keeps the body short, and it matches every answer where the widest pair is not the winner. Watch it on [4, 3, 2, 1, 4], where the two ends are the answer.","workspacePanel":"trace","pitfall":"The code below advances a pointer at the top of the loop, then measures the pair it lands on.","whyItMatters":"Moving before measuring skips the very first pair, the widest container. On [4, 3, 2, 1, 4] that pair holds 16, the answer, and it is gone before any area is computed. Measure the current pair first, then move.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"left, right = 0, len(height) - 1\nbest = 0\nwhile left < right:\n    if height[left] < height[right]:\n        left += 1\n    else:\n        right -= 1\n    area = min(height[left], height[right]) * (right - left)\n    if area > best:\n        best = area\nreturn best","steps":[{"id":"skip-measure","title":"It moves at the top, before measuring","codeLine":6,"summary":"height = [4, 3, 2, 1, 4]. The ends are equal, so the loop takes the else branch and steps right inward, all before any area is computed.","state":{"nums":[4,3,2,1,4],"left":0,"right":4,"best":0,"labels":{"nums":"height"}}},{"id":"endpoint-lost","title":"The endpoint pair is gone unmeasured","codeLine":8,"summary":"right is now at index 3 (height 1). The first area the code measures is min(4, 1) times 3 = 3. The widest pair, the two 4s holding 16, was never measured.","state":{"nums":[4,3,2,1,4],"left":0,"right":3,"best":3,"labels":{"nums":"height"}}},{"id":"stuck-low","title":"best finishes at 4, not 16","codeLine":10,"summary":"The scan walks right inward to index 1, and the best area it ever records is 4. The true answer of 16, sitting at the endpoints it skipped, is never seen.","state":{"nums":[4,3,2,1,4],"left":0,"right":1,"best":4,"labels":{"nums":"height"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let [left, right] = [0, (height.length - 1)];\nlet best = 0;\nwhile (left < right) {\n    if (height[left] < height[right]) {\n        left++;\n    } else {\n        right--;\n    }\n    const area = Math.min(height[left], height[right]) * (right - left);\n    if (area > best) {\n        best = area;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":14},"statementBundles":{"7":{"startLine":7,"endLine":8},"10":{"startLine":11,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let [left, right] = [0, (height.length - 1)];\nlet best = 0;\nwhile (left < right) {\n    if (height[left] < height[right]) {\n        left++;\n    } else {\n        right--;\n    }\n    const area = Math.min(height[left], height[right]) * (right - left);\n    if (area > best) {\n        best = area;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":14},"statementBundles":{"7":{"startLine":7,"endLine":8},"10":{"startLine":11,"endLine":13}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int left = 0;\nint right = (height.size() - 1);\nint best = 0;\nwhile (left < right) {\n    if (height.get(left) < height.get(right)) {\n        left++;\n    } else {\n        right--;\n    }\n    int area = Math.min(height.get(left), height.get(right)) * (right - left);\n    if (area > best) {\n        best = area;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":3,"3":4,"4":5,"5":6,"6":7,"7":8,"8":10,"9":11,"10":12,"11":15},"statementBundles":{"1":{"startLine":1,"endLine":2},"7":{"startLine":8,"endLine":9},"10":{"startLine":12,"endLine":14}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"var (left, right) = (0, height.Count - 1);\nint best = 0;\nwhile (left < right) {\n    if (height[left] < height[right]) {\n        left++;\n    } else {\n        right--;\n    }\n    int area = Math.Min(height[left], height[right]) * (right - left);\n    if (area > best) {\n        best = area;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":14},"statementBundles":{"7":{"startLine":7,"endLine":8},"10":{"startLine":11,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int left = 0;\nint right = (height.size() - 1);\nint best = 0;\nwhile (left < right) {\n    if (height[left] < height[right]) {\n        left++;\n    } else {\n        right--;\n    }\n    int area = min(height[left], height[right]) * (right - left);\n    if (area > best) {\n        best = area;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":3,"3":4,"4":5,"5":6,"6":7,"7":8,"8":10,"9":11,"10":12,"11":15},"statementBundles":{"1":{"startLine":1,"endLine":2},"7":{"startLine":8,"endLine":9},"10":{"startLine":12,"endLine":14}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Closing two pointers inward and always moving the shorter wall swept out the widest container in a single pass.","Shrink the input to its limits: only two walls left, and a wall whose height is zero."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":0,"right":8,"best":0,"labels":{"nums":"height"}}}]}},{"id":"two-walls-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"With only two walls, what is the answer?","summary":"height = [4, 9].","workspacePanel":"visualizer","options":[{"id":"four","label":"4","rationale":"min(4, 9) times the width 1 is 4. With one pair, the loop measures it once and returns it.","isCorrect":true},{"id":"nine","label":"9","rationale":"The shorter wall has height 4, so the cap is 4. The area is 4 * 1 = 4.","isCorrect":false},{"id":"thirteen","label":"13","rationale":"Heights are not added. The water is the shorter height times the width: 4 times 1.","isCorrect":false}],"answer":"4. The only container is min(4, 9) times the width 1, which is 4.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-walls-state","state":{"nums":[4,9],"left":0,"right":1,"best":4,"labels":{"nums":"height"}}}]}},{"id":"zero-wall-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What does a wall of height 0 hold?","summary":"One of the two walls has height 0.","workspacePanel":"visualizer","options":[{"id":"none","label":"No water, whatever the other wall","rationale":"Water is capped by the shorter wall, and a height-0 wall caps it at 0. The pair holds nothing, so the shorter wall is the one to move.","isCorrect":true},{"id":"other-height","label":"As much as the taller wall allows","rationale":"The taller wall does not matter when the shorter is 0. Water spills over the empty side, so the area is 0.","isCorrect":false},{"id":"average","label":"The average of the two heights","rationale":"The shorter height is 0, so the area is 0 * width = 0.","isCorrect":false}],"answer":"0. The shorter wall caps the water, and a height-0 wall caps it at nothing, so that wall moves on.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-wall-edge-state","state":{"nums":[0,8],"left":0,"right":1,"best":0,"labels":{"nums":"height"}}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Two walls closing inward","summary":"Always move the shorter wall; moving the taller one cannot help.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"nums":[1,8,6,2,5,4,8,3,7],"left":0,"right":8,"best":0,"labels":{"nums":"height"}}}]},"body":["Put one pointer at each end. Measure the water between them, keep the best, and move the shorter wall inward, repeating until the pointers meet."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the shrinking-width search","eyebrow":"Code the rule","summary":"Now write it: put a pointer at each end with the best area at zero, then in the loop measure width times the shorter wall, raise the best, move the shorter pointer inward, and return the best once the pointers meet.","workspacePanel":"code","checkpoints":[{"id":"init-pointers","title":"Initialize opposite pointers","description":"Place one pointer at each end of the array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"initializes_boundary_pointers","scope":"init-pointers","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Starting both pointers at the same side","Starting the right pointer at len(height) instead of len(height) - 1"],"hint":"The widest possible container is the first candidate.","semanticSpec":{"intent":"Initialize opposite boundary pointers so the first candidate uses the widest possible container.","doneWhen":"This step is done when one pointer starts at index 0 and the other starts at the last index before the inward scan begins.","shouldFailWhen":"This step should fail if both pointers start on the same side, if the right pointer is not tied to the end of the array, or if the algorithm starts with a narrowed window.","roles":["left pointer","right pointer","height array","widest candidate"],"mustProve":["The left boundary starts at the first index.","The right boundary starts at the last valid index.","The pointers are initialized before the convergence loop."],"mustNotAccept":["Starting right at `len(height)`.","Starting from arbitrary interior positions.","Using nested all-pairs loops instead of boundary pointers."],"equivalentVariants":["Use `left = 0` and `right = len(height) - 1`.","Use equivalent pointer variables seeded to the two ends of the height array."],"proofSnippets":[{"id":"py-container-init-pointers","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    while left < right:\n        return 0\n    return 0"}]}},{"id":"compute-area","title":"Compute current area","description":"At each step, compute width times the shorter boundary height.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"computes_boundary_width_extremum_contribution","scope":"compute-area","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Using the taller height","Forgetting width is right - left"],"hint":"Water can only rise to the shorter wall.","semanticSpec":{"intent":"Compute the area for the current pair from the pointer distance and the shorter boundary height.","doneWhen":"This step is done when each loop iteration derives width from the two pointers, derives height from the smaller boundary value, and forms their product.","shouldFailWhen":"This step should fail if the code uses the taller boundary as the water height, forgets the width, uses adjacent distance only, or computes area after moving a pointer without checking the current pair.","roles":["left pointer","right pointer","width","shorter boundary height","current area"],"mustProve":["Width is derived from the distance between the two current pointers.","Container height is derived from the minimum of the two boundary heights.","The current area is width multiplied by that limiting height."],"mustNotAccept":["Using `max(height[left], height[right])` for the water height.","Using only height and ignoring width.","Computing area from non-boundary values."],"equivalentVariants":["Use `width = right - left` and `area = width * min(height[left], height[right])`.","Use equivalent inline arithmetic that preserves the same width and limiting-height semantics."],"neededLowerLayerFact":{"suggestedFamily":"two-pointer","suggestedFact":"computes_boundary_width_extremum_area","suggestedScope":"compute-area","owner":"Layer 5A structural fact plus Layer 6 familyFact reader"},"proofSnippets":[{"id":"py-container-compute-area","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    while left < right:\n        width = right - left\n        area = width * min(height[left], height[right])\n        return area\n    return 0"}]}},{"id":"update-best","title":"Track maximum area","description":"Update the best area after evaluating each pointer pair.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"updates_boundary_accumulation_extremum","scope":"update-best","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving pointers before checking area","Returning only the last area"],"hint":"Record the best area seen so far.","semanticSpec":{"intent":"Maintain a best-area accumulator for the maximum container area seen so far.","doneWhen":"This step is done when a numeric best state is initialized before the loop and updated from current candidate areas during the scan.","shouldFailWhen":"This step should fail if no best state exists, if the result returns only the last area, or if the update is not tied to the boundary scan.","roles":["best area","current area","boundary scan","numeric accumulator"],"mustProve":["A numeric result state is initialized before the scan.","The scan updates that state from candidate boundary contributions.","The result state is separate from the pointer variables."],"mustNotAccept":["Returning the final current area only.","Using a pointer as the best-area accumulator.","Updating best before computing any candidate contribution."],"equivalentVariants":["Use `best = max(best, area)`.","Use an equivalent conditional update when the current area exceeds the best area."],"semanticFactNote":"This existing fact proves boundary accumulation state, but a later directional-area fact should make the current-area coupling more precise.","neededLowerLayerFact":{"suggestedFamily":"two-pointer","suggestedFact":"updates_best_from_boundary_area","suggestedScope":"update-best","owner":"Layer 5A numeric extremum/update relation plus Layer 6 two-pointer fact reader"},"proofSnippets":[{"id":"py-container-update-best","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    max_area = 0\n    while left < right:\n        width = right - left\n        area = width * min(height[left], height[right])\n        max_area = max(max_area, area)\n        return 0\n    return 0"}]}},{"id":"move-shorter","title":"Move the limiting side","description":"Move the pointer at the shorter height inward.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"moves_smaller_boundary_inward","scope":"move-shorter","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving the taller side and keeping the same limiter","Moving both pointers every time"],"hint":"Only moving the shorter side can reveal a taller limiting wall.","semanticSpec":{"intent":"Move inward from the shorter boundary because that side limits the current container height.","doneWhen":"This step is done when the loop compares the two boundary heights and advances the pointer on the smaller side inward.","shouldFailWhen":"This step should fail if the taller side is always moved, both pointers move unconditionally, or movement is unrelated to the boundary-height comparison.","roles":["left boundary height","right boundary height","limiting side","inward pointer movement"],"mustProve":["The branch compares the current left and right boundary heights.","The selected movement is based on the smaller limiting boundary.","Pointer movement keeps the scan converging inward."],"mustNotAccept":["Moving both pointers every iteration.","Moving the taller boundary because it is taller.","Changing pointers without comparing boundary heights."],"equivalentVariants":["Use `if height[left] < height[right]: left += 1 else: right -= 1`.","Use the symmetric comparison with equivalent shorter-side movement."],"neededLowerLayerFact":{"suggestedFamily":"two-pointer","suggestedFact":"advances_shorter_boundary_pointer","suggestedScope":"move-shorter","owner":"Layer 5A pointer movement relation plus Layer 6 two-pointer fact reader"},"proofSnippets":[{"id":"py-container-move-shorter","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    max_area = 0\n    while left < right:\n        width = right - left\n        area = width * min(height[left], height[right])\n        max_area = max(max_area, area)\n        if height[left] < height[right]:\n            left += 1\n        else:\n            right -= 1\n    return 0"}]}},{"id":"return-best","title":"Return the best area","description":"Return the maximum area found after the two pointers finish converging.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"returns_boundary_accumulation_result","scope":"return-best","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Returning the last computed area instead of the best one","Returning a pointer index instead of the area"],"hint":"Return the tracked maximum after the pointers meet.","semanticSpec":{"intent":"Return the maximum container area tracked during the boundary-converging scan.","doneWhen":"This step is done when the function returns the best area state after the pointer loop completes.","shouldFailWhen":"This step should fail if the code returns the last area, a pointer, or an uninitialized value.","roles":["best area","terminal return","two-pointer scan"],"mustProve":["A best-area state is tracked during the scan.","The returned value is that best-area state after convergence."],"mustNotAccept":["Returning the current area from only the final pointer position.","Returning left or right pointer indices."],"equivalentVariants":["Return max_area after the loop.","Return an equivalent best-area accumulator."],"proofSnippets":[{"id":"py-container-return-best","language":"python","code":"def maxArea(height: list[int]) -> int:\n    left, right = 0, len(height) - 1\n    max_area = 0\n    while left < right:\n        area = (right - left) * min(height[left], height[right])\n        max_area = max(max_area, area)\n        if height[left] < height[right]:\n            left += 1\n        else:\n            right -= 1\n    return max_area"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Start as wide as possible; move the shorter wall inward, since only it can let you gain.","workspacePanel":"code","body":["Water held by two walls is the shorter wall times the width, so begin at the widest pair and hunt for height that beats it.","Moving the taller wall can never help, since the short one still caps the water, so always move the shorter wall."],"takeaways":[{"title":"The short wall is the bottleneck","body":"Area is capped by the shorter side, so only moving that side has any chance of a taller minimum."},{"title":"Width is spent for height","body":"Each step trades width away, so it only pays off when a taller wall more than makes up the loss."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"executionStyle":"solution-method","syntheticTestConfig":{"inputShape":"array","primaryParam":"height","sizeMetric":"length","constraints":["non-negative"],"valueRange":{"min":0,"max":100}}}
