{"id":"longest-harmonious-subsequence","title":"Longest Harmonious Subsequence","difficulty":"easy","patterns":["hash-map"],"primaryConcept":"hash-map-grouping","concepts":["hash-map-grouping"],"problemForm":"core","companies":["Amazon","Google","Microsoft"],"category":"hash-tables","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length","valueRange":{"min":-50,"max":50},"sizes":[8,16,32,64]},"description":"Given an integer array `nums`, return the length of the longest harmonious subsequence.\n\nA harmonious subsequence is a subsequence where the difference between its maximum value and minimum value is exactly `1`. You may delete elements, but the remaining values keep their original relative order.","examples":[{"input":"nums = [1,3,2,2,5,2,3,7]","output":"5","explanation":"The longest harmonious subsequence contains three 2s and two 3s."},{"input":"nums = [1,2,3,4]","output":"2","explanation":"Any adjacent value pair, such as 1 and 2, gives length 2."},{"input":"nums = [1,1,1,1]","output":"0","explanation":"The max and min would be equal, so no harmonious subsequence exists."}],"constraints":[{"id":"1-len-nums-2-10-4","text":"1 <= len(nums) <= 2 * 10^4","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":20000}},{"id":"10-9-nums-i-10-9","text":"-10^9 <= nums[i] <= 10^9","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-1000000000,"max":1000000000}}],"starterCode":"class Solution:\n    def findLHS(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"findLHS","testCases":[{"id":"1","input":{"nums":[1,3,2,2,5,2,3,7]},"expected":5,"description":"Standard case with the best pair 2 and 3."},{"id":"2","input":{"nums":[1,2,3,4]},"expected":2,"description":"Every adjacent value pair has one occurrence each."},{"id":"3","input":{"nums":[1,1,1,1]},"expected":0,"description":"A single distinct value cannot be harmonious."},{"id":"4","input":{"nums":[1,1,1,2,2,3]},"expected":5,"description":"Use the most frequent adjacent pair."},{"id":"5","input":{"nums":[-1,0,-1,0,-1,1]},"expected":5,"description":"Negative values work the same way."},{"id":"h1","input":{"nums":[1,2,2,1]},"expected":4,"description":"All values belong to one harmonious pair."},{"id":"h2","input":{"nums":[10,12,11,11,12,12,13]},"expected":5,"description":"The pair 11 and 12 beats 12 and 13."},{"id":"h3","input":{"nums":[100]},"expected":0,"description":"Single element has no max-min difference of one."},{"id":"h4","input":{"nums":[1,3,5,7]},"expected":0,"description":"No adjacent values means no harmonious subsequence."},{"id":"h5","input":{"nums":[4,4,5,5,5,6]},"expected":5,"description":"The pair 4 and 5 yields the longest valid subsequence."}],"hints":[{"level":1,"content":"The subsequence order does not affect the length; only value counts matter.","revealPattern":false},{"level":2,"content":"Count how often each value appears, then try each value as the smaller member of the pair.","revealPattern":true},{"level":3,"content":"For value `x`, a harmonious pair exists only if `x + 1` also appears.","revealPattern":true}],"guidedFlow":{"version":2,"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":"sort-and-window","name":"Sort and scan","summary":"Sort the values, then scan contiguous groups whose values differ by one.","decisionReason":"Sorting does group neighboring values, but it pays O(n log n) up front before any scanning. A frequency map gets the same counts in one O(n) pass and checks each neighbor in O(1), so the sort buys nothing the map does not already give.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Runs in O(n log n) time and uses O(n) space."],"isOptimal":false},{"id":"frequency-map","name":"Count values and check neighbors","summary":"Build a frequency map, then combine each count with the count for the next value.","decisionReason":"A harmonious pick is fully described by two numbers: how many copies of v and how many of v+1. The frequency map holds both, so each key answers its own question in O(1) after one read of the array.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-frequency-map","title":"Create the frequency map","description":"Initialize a keyed counter for the values in `nums`.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"initializes_keyed_state","scope":"init-frequency-map","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Trying to preserve subsequence order","Using a set and losing multiplicity"],"hint":"The answer depends on how many times each value appears.","semanticSpec":{"intent":"Initialize keyed frequency state.","doneWhen":"A map-like state exists to store value counts.","shouldFailWhen":"This step should fail if no keyed state is initialized.","roles":["frequency map","input values"],"mustProve":["The solution initializes keyed state for counting."],"mustNotAccept":["A set-only representation that discards counts."],"proofSnippets":[{"id":"py-lhs-init-frequency-map","language":"python","code":"class Solution:\n    def findLHS(self, nums: list[int]) -> int:\n        counts = {}"}]}},{"id":"scan-nums","title":"Scan the input values","description":"Visit every value in `nums` to count its frequency.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Skipping duplicate values","Stopping after finding one adjacent pair"],"hint":"Every occurrence contributes to a pair's total length.","semanticSpec":{"intent":"Scan the input sequence for counting.","doneWhen":"The solution iterates over the input values.","shouldFailWhen":"This step should fail if the input sequence is not traversed.","roles":["input sequence","current value"],"mustProve":["The traversal reads values from `nums`."],"mustNotAccept":["A fixed loop unrelated to the input."],"proofSnippets":[{"id":"py-lhs-scan-nums","language":"python","code":"class Solution:\n    def findLHS(self, nums: list[int]) -> int:\n        counts = {}\n        for num in nums:\n            pass"}]}},{"id":"count-frequencies","title":"Count each value","description":"Increment the frequency for the current value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"counts_items_by_key","scope":"count-frequencies","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Overwriting the count with 1 each time","Counting indices instead of values"],"hint":"Use `get(..., 0) + 1` or an equivalent counter update.","semanticSpec":{"intent":"Maintain value frequencies in keyed state.","doneWhen":"Each input value increments its frequency bucket.","shouldFailWhen":"This step should fail if repeated values are not accumulated.","roles":["frequency map","current value"],"mustProve":["The keyed state is incremented by key during the scan."],"mustNotAccept":["A write that replaces the count without reading the old count."],"proofSnippets":[{"id":"py-lhs-count-frequencies","language":"python","code":"class Solution:\n    def findLHS(self, nums: list[int]) -> int:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1"}]}},{"id":"init-best","title":"Start with no valid pair","description":"Initialize the best answer to 0 because a single distinct value is not harmonious.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Initializing the answer to 1","Returning a nonzero answer for all-equal arrays"],"hint":"No valid pair means answer 0.","semanticSpec":{"intent":"Initialize the numeric answer state.","doneWhen":"The best length starts at zero.","shouldFailWhen":"This step should fail if the answer starts at a positive value.","roles":["best length"],"mustProve":["The answer state is initialized to zero."],"mustNotAccept":["An answer initialized to one."],"proofSnippets":[{"id":"py-lhs-init-best","language":"python","code":"class Solution:\n    def findLHS(self, nums: list[int]) -> int:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        best = 0"}]}},{"id":"check-neighbor","title":"Check the next value","description":"For each value `x`, check whether `x + 1` exists in the frequency map.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"checks_key_membership","scope":"check-adjacent-key-in-map","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Combining values with difference greater than one","Checking `x - 1` and `x + 1` then double counting"],"hint":"Treat the current value as the smaller value in the pair.","semanticSpec":{"intent":"Use keyed membership to find adjacent value buckets.","doneWhen":"The solution checks whether the frequency map contains a neighboring key.","shouldFailWhen":"This step should fail if no keyed membership check is used.","roles":["current value","neighbor value","frequency map"],"mustProve":["The algorithm checks an adjacent key derived from the current frequency-map key."],"mustNotAccept":["Combining counts without verifying the adjacent key exists."],"proofSnippets":[{"id":"py-lhs-check-neighbor","language":"python","code":"class Solution:\n    def findLHS(self, nums: list[int]) -> int:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        best = 0\n        for num, freq in counts.items():\n            if num + 1 in counts:\n                neighbor_count = counts[num + 1]"}]}},{"id":"update-best","title":"Update the longest length","description":"When a neighbor exists, combine the two frequencies and keep the maximum.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Using only the larger bucket's count","Overwriting the best length with the last pair"],"hint":"The subsequence can include every occurrence of both adjacent values.","semanticSpec":{"intent":"Track the maximum combined adjacent frequency.","doneWhen":"The best answer is updated with an extremum comparison.","shouldFailWhen":"This step should fail if the best answer is not compared against candidate lengths.","roles":["candidate length","best length"],"mustProve":["The solution updates the numeric extremum state."],"mustNotAccept":["A plain assignment from the last candidate."],"proofSnippets":[{"id":"py-lhs-update-best","language":"python","code":"class Solution:\n    def findLHS(self, nums: list[int]) -> int:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        best = 0\n        for num, freq in counts.items():\n            if num + 1 in counts:\n                best = max(best, freq + counts[num + 1])"}]}},{"id":"return-best","title":"Return the best length","description":"Return the accumulated best harmonious subsequence length.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning the frequency map","Returning the count for the current value"],"hint":"The best accumulator is already 0 if no pair was found.","semanticSpec":{"intent":"Return the terminal accumulated answer.","doneWhen":"The final return is the best length after all keyed entries are checked.","shouldFailWhen":"This step should fail if a temporary count or map is returned.","roles":["best length","return value"],"mustProve":["The function returns the terminal accumulator."],"mustNotAccept":["Returning keyed state instead of the answer."],"proofSnippets":[{"id":"py-lhs-return-best","language":"python","code":"class Solution:\n    def findLHS(self, nums: list[int]) -> int:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        best = 0\n        for num, freq in counts.items():\n            if num + 1 in counts:\n                best = max(best, freq + counts[num + 1])\n        return best"}]}}],"slides":[{"id":"read-the-problem","chapter":"The task","kind":"info","eyebrow":"Read the problem","title":"A range of exactly one","workspacePanel":"problem","body":["You get a list of numbers. Pick a subsequence by keeping some numbers, dropping the rest, and leaving the kept ones in their original order. Its largest value and smallest value must differ by exactly 1. Return how long the longest such subsequence can be.","The obvious way to find the best pair is to try every value as the smaller half and count the matching values."]},{"id":"brute-force","chapter":"The task","kind":"code-trace","eyebrow":"The obvious way","title":"Recount for every value","summary":"Trying every value as the smaller half finds the right pair, but it recounts the same values over and over. Watch how often the array gets re-walked.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"best = 0\nfor x in set(nums):\n    low = sum(1 for v in nums if v == x)\n    high = sum(1 for v in nums if v == x + 1)\n    if high > 0:\n        best = max(best, low + high)\nreturn best","steps":[{"id":"count-one","title":"Try 1 as the smaller value","codeLine":3,"summary":"nums = [1,3,2,2,5,2,3,7]. Walk all eight values to count the 1s, then walk all eight again to count the 2s: one 1, three 2s.","state":{"nums":[1,3,2,2,5,2,3,7],"current":0}},{"id":"pair-one","title":"Combine the pair for 1","codeLine":6,"summary":"1 + 3 = 4, a valid pairing of values 1 and 2. best rises to 4.","state":{"nums":[1,3,2,2,5,2,3,7],"current":0}},{"id":"count-two","title":"Try 2, recounting from scratch","codeLine":3,"summary":"Now x is 2. The eight values are scanned again for 2s, then again for 3s, even though the 2s were already counted a moment ago.","state":{"nums":[1,3,2,2,5,2,3,7],"current":2}},{"id":"pair-two","title":"The best pair, found by walking the list twice more","codeLine":6,"summary":"Three 2s and two 3s give 5. Every distinct value triggers two more full scans of nums.","state":{"nums":[1,3,2,2,5,2,3,7],"current":2}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let best = 0;\nfor (const x of new Set(nums)) {\n    let total = 0;\n    for (const v of nums) {\n        if (v === x) {\n            total++;\n        }\n    }\n    const low = total;\n    let total1 = 0;\n    for (const v of nums) {\n        if (v === (x + 1)) {\n            total1++;\n        }\n    }\n    const high = total1;\n    if (high > 0) {\n        best = Math.max(best, (low + high));\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":10,"5":17,"6":18,"7":21},"statementBundles":{"3":{"startLine":3,"endLine":9},"4":{"startLine":10,"endLine":16},"6":{"startLine":18,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let best = 0;\nfor (const x of new Set(nums)) {\n    let total = 0;\n    for (const v of nums) {\n        if (v === x) {\n            total++;\n        }\n    }\n    const low = total;\n    let total1 = 0;\n    for (const v of nums) {\n        if (v === (x + 1)) {\n            total1++;\n        }\n    }\n    const high = total1;\n    if (high > 0) {\n        best = Math.max(best, (low + high));\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":10,"5":17,"6":18,"7":21},"statementBundles":{"3":{"startLine":3,"endLine":9},"4":{"startLine":10,"endLine":16},"6":{"startLine":18,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int best = 0;\nfor (Integer x : new HashSet<Integer>(nums)) {\n    int total = 0;\n    for (Integer v : nums) {\n        if (v == x) {\n            total++;\n        }\n    }\n    int low = total;\n    int total1 = 0;\n    for (Integer v : nums) {\n        if (v == (x + 1)) {\n            total1++;\n        }\n    }\n    int high = total1;\n    if (high > 0) {\n        best = Math.max(best, (low + high));\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":10,"5":17,"6":18,"7":21},"statementBundles":{"3":{"startLine":3,"endLine":9},"4":{"startLine":10,"endLine":16},"6":{"startLine":18,"endLine":20}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int best = 0;\nforeach (int x in new HashSet<int>(nums)) {\n    int total = 0;\n    foreach (int v in nums) {\n        if (v == x) {\n            total++;\n        }\n    }\n    int low = total;\n    int total1 = 0;\n    foreach (int v in nums) {\n        if (v == x + 1) {\n            total1++;\n        }\n    }\n    int high = total1;\n    if (high > 0) {\n        best = Math.Max(best, low + high);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":10,"5":17,"6":18,"7":21},"statementBundles":{"3":{"startLine":3,"endLine":9},"4":{"startLine":10,"endLine":16},"6":{"startLine":18,"endLine":20}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int best = 0;\nfor (int x : unordered_set<int>(nums.begin(), nums.end())) {\n    int total = 0;\n    for (int v : nums) {\n        if (v == x) {\n            total++;\n        }\n    }\n    int low = total;\n    int total1 = 0;\n    for (int v : nums) {\n        if (v == (x + 1)) {\n            total1++;\n        }\n    }\n    int high = total1;\n    if (high > 0) {\n        best = max(best, (low + high));\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":10,"5":17,"6":18,"7":21},"statementBundles":{"3":{"startLine":3,"endLine":9},"4":{"startLine":10,"endLine":16},"6":{"startLine":18,"endLine":20}}}}},"body":["For each distinct value, scan the whole array twice: once for that value, once for the value one higher."]},{"id":"cost-probe","chapter":"The task","kind":"case-probe","eyebrow":"Count the cost","title":"How much work for n distinct values?","summary":"Each value triggers two full sweeps of nums, and a long list can be all distinct.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sweep-for-1","title":"Value 1: two full sweeps","summary":"To count 1 and its neighbor 2, walk all five values twice. 2 sweeps so far.","state":{"nums":[1,2,3,4,5],"current":0,"sweepsSoFar":2}},{"id":"sweep-for-2","title":"Value 2: two more sweeps","summary":"Now count 2 and 3 with two fresh passes over the whole array. Four sweeps so far.","state":{"nums":[1,2,3,4,5],"current":1,"sweepsSoFar":4}},{"id":"sweep-for-3","title":"Value 3: two more sweeps","summary":"Count 3 and 4 with two more full passes. 6 sweeps so far.","state":{"nums":[1,2,3,4,5],"current":2,"sweepsSoFar":6}},{"id":"sweep-for-5","title":"Value 5: still two more","summary":"Every distinct value costs two passes; with 5 distinct values that is 10 sweeps of 5 elements.","state":{"nums":[1,2,3,4,5],"current":4,"sweepsSoFar":10}}]},"options":[{"id":"n-squared","label":"Roughly n sweeps of n values, about n squared","rationale":"Every distinct value walks the whole list to count itself and its neighbor. With n distinct values that is n passes over n elements.","isCorrect":true},{"id":"linear","label":"One pass, since each value is visited once","rationale":"Each value is the smaller half once, but counting it re-reads the entire array. The visits are nested, not flat.","isCorrect":false},{"id":"log-linear","label":"About n log n, like a sort","rationale":"Nothing here sorts or halves a range. The cost comes from repeating a full count for every value.","isCorrect":false}],"answer":"Each distinct value re-walks the array to count, so the work grows with n times n. The same counts are recomputed again and again."},{"id":"insight-probe","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the waste","title":"Which question kills the recounting?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rescan-waste","title":"The waste: re-asking the same count","summary":"The brute force re-walks the whole array every time it needs how many of a value there are. counts is still empty.","state":{"nums":[1,3,2,2,5,2,3,7],"current":2,"seen":{},"labels":{"seen":"counts"}}},{"id":"tally-once","title":"Tally once, answer forever","summary":"One pass records how many times each value appears. Now every pairing is count[x] + count[x + 1] with no rescanning.","state":{"nums":[1,3,2,2,5,2,3,7],"seen":{"1":1,"2":3,"3":2,"5":1,"7":1},"labels":{"seen":"counts"}}}]},"quiz":{"contract":"pattern-recognition-v1","question":"Which question kills the recounting?","signalPrompt":"The brute force re-walks the array to ask the same thing each time. What single piece of state, computed once, would answer every pairing instantly?","options":[{"id":"frequency-map","label":"How many times does each value appear?","signal":"Every candidate answer is just one count plus the count of the next value up.","rationale":"Tally the values once into a map, and each pairing becomes count[x] + count[x + 1] with no rescanning.","isCorrect":true},{"id":"is-sorted","label":"What order do the values come in?","signal":"Order looks relevant because it is a subsequence.","rationale":"The kept length depends only on how many of each value exist, not where they sit, so order answers nothing here.","isCorrect":false},{"id":"running-max","label":"What is the largest value so far?","signal":"A running maximum summarizes the scan in one number.","rationale":"The maximum says nothing about how many copies of a specific value or its neighbor exist.","isCorrect":false},{"id":"prefix-sums","label":"What is the running sum up to each index?","signal":"Prefix sums answer range-total questions in O(1).","rationale":"The answer is about counts of equal values, not sums over index ranges, so a prefix sum is the wrong precomputation.","isCorrect":false}],"missFeedback":"The repeated work is counting copies of a value. State the count once and the pairing is immediate."}},{"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-counts","state":{"seen":{"1":1,"2":3,"3":2,"5":1,"7":1},"labels":{"seen":"counts"}}}]}},{"id":"state-meaning","chapter":"The idea","kind":"case-probe","eyebrow":"Set up the state","title":"What does each entry in counts hold?","summary":"Call the tally counts: one entry per distinct value.","workspacePanel":"visualizer","options":[{"id":"value-to-frequency","label":"A value, mapped to how many times it appears","rationale":"count[x] + count[x + 1] is the whole answer, so each entry has to record the frequency of one value.","isCorrect":true},{"id":"value-to-index","label":"A value, mapped to the last index it appeared at","rationale":"An index says where a value sits, but the length depends on how many copies exist, not their positions.","isCorrect":false},{"id":"index-to-value","label":"An index, mapped to the value stored there","rationale":"That is just the array again. Keying by index keeps the order the problem already told us to ignore.","isCorrect":false}],"answer":"counts maps each distinct value to its frequency, so the only thing left to do is add neighboring counts.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-meaning-counts","state":{"nums":[1,3,2,2,5,2,3,7],"seen":{"1":1,"2":3,"3":2,"5":1,"7":1},"labels":{"seen":"counts"}}}]}},{"id":"pairing-rule","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"When does a value contribute a length?","summary":"counts holds {1:1, 2:3, 3:2, 5:1, 7:1}; take value 5 as the smaller half.","workspacePanel":"visualizer","options":[{"id":"needs-neighbor","label":"Only when value + 1 is also in counts","rationale":"A range of exactly 1 needs both values present. counts has 5 but no 6, so 5 contributes nothing.","isCorrect":true},{"id":"always-counts","label":"Always; its own count is a valid length","rationale":"A lone value has max equal to min, a difference of 0, not 1. One value alone is never harmonious.","isCorrect":false},{"id":"needs-both-neighbors","label":"Only when value - 1 and value + 1 both exist","rationale":"A harmonious pair spans just two adjacent values. Requiring both neighbors would reject valid pairs like 2 and 3.","isCorrect":false}],"answer":"A value pairs only when value + 1 exists too. counts has 5 but no 6, so 5 is skipped; treating each value as the smaller half checks every pair exactly once.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pairing-rule-state","state":{"nums":[1,3,2,2,5,2,3,7],"seen":{"1":1,"2":3,"3":2,"5":1,"7":1},"seenHighlight":5,"labels":{"seen":"counts"}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Counts built, best at zero","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[1,3,2,2,5,2,3,7],"seen":{"1":1,"2":3,"3":2,"5":1,"7":1},"best":0,"labels":{"seen":"counts"}}}]},"body":["One pass has already tallied the values into counts. best starts at 0 because nothing harmonious has been found yet.","Now walk the distinct values. For each one, look up value + 1; if it is there, the combined count is a candidate length and best keeps the largest seen."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the pairs","title":"Walk the counts","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pair-1-2","state":{"nums":[1,3,2,2,5,2,3,7],"seen":{"1":1,"2":3,"3":2,"5":1,"7":1},"seenHighlight":1,"best":0,"labels":{"seen":"counts"}}},{"id":"pair-2-3","state":{"nums":[1,3,2,2,5,2,3,7],"seen":{"1":1,"2":3,"3":2,"5":1,"7":1},"seenHighlight":2,"best":4,"labels":{"seen":"counts"}}},{"id":"value-5-skipped","state":{"nums":[1,3,2,2,5,2,3,7],"seen":{"1":1,"2":3,"3":2,"5":1,"7":1},"seenHighlight":5,"best":5,"labels":{"seen":"counts"}}}]},"beats":[{"id":"pair-1-2","title":"At value 1, what candidate length appears?","summary":"Value 1 is being checked as the smaller half; best is still 0.","options":[{"id":"one-plus-three","label":"1 + 3 = 4","rationale":"Value 1 keeps its single copy and value 2 keeps all three, so the pair is length 4 and best rises to 4.","isCorrect":true},{"id":"just-one","label":"1, the count of value 1 alone","rationale":"A single value is not harmonious. The candidate combines value 1 with its neighbor 2.","isCorrect":false},{"id":"three-only","label":"3, the count of value 2 alone","rationale":"Both halves are kept. The length is count[1] + count[2].","isCorrect":false}],"answer":"count[1] + count[2] = 1 + 3 = 4. best moves from 0 to 4."},{"id":"pair-2-3","title":"At value 2, what happens to best?","summary":"Value 2 is being checked as the smaller half; best is 4 from the previous pair.","options":[{"id":"rises-to-five","label":"The candidate is 5, so best becomes 5","rationale":"Three 2s plus two 3s is 5, which beats the stored 4, so best updates.","isCorrect":true},{"id":"stays-four","label":"best stays 4 because it already found a pair","rationale":"best keeps the maximum across all pairs. A larger candidate must replace the earlier value.","isCorrect":false},{"id":"adds-up","label":"best becomes 9, adding this pair to the last","rationale":"Pairs are not summed together. Each pairing is its own candidate and best takes the largest.","isCorrect":false}],"answer":"count[2] + count[3] = 3 + 2 = 5, which is larger than 4, so best becomes 5."},{"id":"value-5-skipped","title":"At value 5, what is the candidate?","summary":"Value 5 is being checked as the smaller half; best is 5.","options":[{"id":"no-candidate","label":"None; 5 has no neighbor, so best stays 5","rationale":"count[6] is absent, so value 5 cannot form a harmonious pair and best is unchanged.","isCorrect":true},{"id":"lone-five","label":"1, the lone count of value 5","rationale":"A single value has a max-min difference of 0, not 1, so it never contributes a length.","isCorrect":false},{"id":"reset","label":"best resets to 0 since this value fails","rationale":"A missing neighbor just skips this value. best holds onto the largest valid pair already found.","isCorrect":false}],"answer":"value + 1 is 6, which is absent from counts, so 5 is skipped and best stays 5."}]},{"id":"lone-bucket-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Does best keep the largest pair, or just the last one?","summary":"Assigning best = count[x] + count[x + 1] for each valid pair always holds a real pairing, but a smaller later pair can overwrite a larger earlier one.","workspacePanel":"trace","pitfall":"The code below assigns each valid pairing straight into best instead of keeping the maximum across pairings.","whyItMatters":"There can be several adjacent pairs, and the answer is the longest of them. Comparing each candidate against the running best with max is what keeps an early long pair from being clobbered by a later short one.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"counts = {}\nfor v in nums:\n    counts[v] = counts.get(v, 0) + 1\nbest = 0\nfor x in counts:\n    if x + 1 in counts:\n        best = counts[x] + counts[x + 1]\nreturn best","steps":[{"id":"counts-built","title":"Three values in the counts","codeLine":4,"summary":"nums = [1,1,1,2,2,3], so counts is {1: 3, 2: 2, 3: 1}. Two adjacent pairs exist: 1 with 2, and 2 with 3.","state":{"nums":[1,1,1,2,2,3],"seen":{"1":3,"2":2,"3":1},"best":0,"labels":{"seen":"counts"}}},{"id":"first-pair-wins","title":"The long pair lands first","codeLine":7,"summary":"At value 1, value 2 exists, so best is assigned count[1] + count[2] = 3 + 2 = 5, the correct answer.","state":{"seen":{"1":3,"2":2,"3":1},"seenHighlight":1,"best":5,"labels":{"seen":"counts"}}},{"id":"later-pair-overwrites","title":"The short pair overwrites it","codeLine":7,"summary":"At value 2, value 3 exists, so best is assigned count[2] + count[3] = 2 + 1 = 3. The plain assignment throws away the 5.","state":{"seen":{"1":3,"2":2,"3":1},"seenHighlight":2,"best":3,"labels":{"seen":"counts"}}},{"id":"wrong-answer","title":"Returns 3, and wrong","codeLine":8,"summary":"The function returns 3 for [1,1,1,2,2,3]. The three 1s and two 2s form a length-5 pair, so the correct answer is 5.","state":{"seen":{"1":3,"2":2,"3":1},"best":3,"labels":{"seen":"counts"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const counts = new Map();\nfor (const v of nums) {\n    counts.set(v, (counts.has(v) ? counts.get(v) : 0) + 1);\n}\nlet best = 0;\nfor (const x of counts.keys()) {\n    if (counts.has((x + 1))) {\n        best = counts.get(x) + counts.get((x + 1));\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10}},"alternateStyles":{"close-to-source":{"code":"const counts = new Map();\nfor (const v of nums) {\n    counts.set(v, (counts.has(v) ? counts.get(v) : 0) + 1);\n}\nlet best = 0;\nfor (const x of counts.keys()) {\n    if (counts.has((x + 1))) {\n        const leftValue = counts.get(x);\n        if (leftValue === undefined) throw new Error(\"KeyError\");\n        best = leftValue + counts.get((x + 1));\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":12}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const counts: Map<number, number> = new Map();\nfor (const v of nums) {\n    counts.set(v, (counts.has(v) ? counts.get(v)! : 0) + 1);\n}\nlet best = 0;\nfor (const x of counts.keys()) {\n    if (counts.has((x + 1))) {\n        best = counts.get(x)! + counts.get((x + 1))!;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10}},"alternateStyles":{"close-to-source":{"code":"const counts: Map<number, number> = new Map();\nfor (const v of nums) {\n    counts.set(v, (counts.has(v) ? counts.get(v)! : 0) + 1);\n}\nlet best = 0;\nfor (const x of counts.keys()) {\n    if (counts.has((x + 1))) {\n        const leftValue = counts.get(x);\n        if (leftValue === undefined) throw new Error(\"KeyError\");\n        best = leftValue + counts.get((x + 1))!;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":12}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"Map<Integer, Integer> counts = new HashMap<Integer, Integer>();\nfor (Integer v : nums) {\n    counts.put(v, (counts.getOrDefault(v, 0) + 1));\n}\nint best = 0;\nfor (Integer x : counts.keySet()) {\n    if (counts.containsKey(x + 1)) {\n        best = counts.get(x) + counts.get(x + 1);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10}},"alternateStyles":{"close-to-source":{"code":"Map<Integer, Integer> counts = new HashMap<Integer, Integer>();\nfor (Integer v : nums) {\n    counts.put(v, (counts.getOrDefault(v, 0) + 1));\n}\nint best = 0;\nfor (Integer x : counts.keySet()) {\n    if (counts.containsKey(x + 1)) {\n        best = requireMapValue(counts, x) + counts.get(x + 1);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10}}}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"Dictionary<int, int> counts = new();\nforeach (int v in nums) {\n    counts[v] = (counts.ContainsKey(v) ? counts[v] : 0) + 1;\n}\nint best = 0;\nforeach (int x in counts.Keys) {\n    if (counts.ContainsKey(x + 1)) {\n        best = counts[x] + counts[x + 1];\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"unordered_map<int, int> counts;\nfor (int v : nums) {\n    counts[v] += 1;\n}\nint best = 0;\nfor (const auto& [x, value] : counts) {\n    if (counts.count((x + 1))) {\n        best = counts.at(x) + counts.at((x + 1));\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"Two inputs could call for special handling: an array of one repeated value, and an array whose values go negative.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-case-baseline","state":{"nums":[-1,0,-1,0,-1,1],"seen":{"0":2,"1":1,"-1":3},"best":0,"labels":{"seen":"counts"}}}]},"body":["An array of one repeated value, and an array whose values go negative.","Each looks like it might deserve special handling. The next two probes decide whether it does."]},{"id":"all-equal-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does an all-equal array return?","summary":"nums = [4,4,4], so counts is {4: 3}.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-equal-state","state":{"nums":[4,4,4],"seen":{"4":3},"seenHighlight":4,"best":0,"labels":{"seen":"counts"}}}]},"options":[{"id":"returns-zero","label":"0, because value 5 is not in counts","rationale":"Value 4 looks up 5, which is absent, so no pairing happens and best stays at its starting 0.","isCorrect":true},{"id":"returns-three","label":"3, the count of the only value","rationale":"A single value has a max-min difference of 0, not 1, so its lone count is never a valid length. The neighbor check looks up value 5, finds nothing, and skips it.","isCorrect":false},{"id":"needs-guard","label":"It needs a special guard for one-value arrays","rationale":"No guard is needed. Requiring value + 1 to exist already returns 0 for a single bucket.","isCorrect":false}],"answer":"Returns 0. The neighbor check does the work: value 5 is absent, so the lone bucket never contributes and best stays 0."},{"id":"negative-values-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Do negative values need handling?","summary":"nums = [-1,0,-1,0,-1,1], so counts is {-1: 3, 0: 2, 1: 1}; take value -1.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"negative-state","state":{"nums":[-1,0,-1,0,-1,1],"seen":{"0":2,"1":1,"-1":3},"seenHighlight":-1,"best":0,"labels":{"seen":"counts"}}}]},"options":[{"id":"no-branch","label":"No: -1 looks up 0 like any other key","rationale":"value + 1 is 0, which is in counts with two copies, so the pair is 3 + 2 = 5. The sign never enters into it.","isCorrect":true},{"id":"needs-offset","label":"Yes: shift everything up so keys stay non-negative","rationale":"A map keys on the raw value, negative or not. Shifting changes the keys for no benefit.","isCorrect":false},{"id":"needs-abs","label":"Yes: compare absolute values to find neighbors","rationale":"Absolute values would pair -1 with 1, whose true difference is 2. The neighbor is value + 1, computed directly.","isCorrect":false}],"answer":"No handling. -1 looks up 0, finds two copies, and the pair is 3 + 2 = 5. A map treats negative keys exactly like any other."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Tally the values once, then pair each one with its neighbor's count.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"nums":[1,3,2,2,5,2,3,7],"seen":{"1":1,"2":3,"3":2,"5":1,"7":1},"best":0,"labels":{"seen":"counts"}}}]},"body":["Tally every value into counts in one pass, start best at 0, then for each value combine its count with the count of the next value up only when that neighbor exists, keeping the largest combined length."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the count-and-pair solution","eyebrow":"Code the rule","summary":"Build it now: one pass that tallies every value, then a sweep of the counts that pairs each value with its neighbor and keeps the longest combined length.","workspacePanel":"code","checkpoints":[{"id":"init-frequency-map","title":"Create the frequency map","description":"Initialize a keyed counter for the values in `nums`.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"initializes_keyed_state","scope":"init-frequency-map","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Trying to preserve subsequence order","Using a set and losing multiplicity"],"hint":"The answer depends on how many times each value appears.","semanticSpec":{"intent":"Initialize keyed frequency state.","doneWhen":"A map-like state exists to store value counts.","shouldFailWhen":"This step should fail if no keyed state is initialized.","roles":["frequency map","input values"],"mustProve":["The solution initializes keyed state for counting."],"mustNotAccept":["A set-only representation that discards counts."]}},{"id":"scan-nums","title":"Scan the input values","description":"Visit every value in `nums` to count its frequency.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Skipping duplicate values","Stopping after finding one adjacent pair"],"hint":"Every occurrence contributes to a pair's total length.","semanticSpec":{"intent":"Scan the input sequence for counting.","doneWhen":"The solution iterates over the input values.","shouldFailWhen":"This step should fail if the input sequence is not traversed.","roles":["input sequence","current value"],"mustProve":["The traversal reads values from `nums`."],"mustNotAccept":["A fixed loop unrelated to the input."]}},{"id":"count-frequencies","title":"Count each value","description":"Increment the frequency for the current value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"counts_items_by_key","scope":"count-frequencies","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Overwriting the count with 1 each time","Counting indices instead of values"],"hint":"Use `get(..., 0) + 1` or an equivalent counter update.","semanticSpec":{"intent":"Maintain value frequencies in keyed state.","doneWhen":"Each input value increments its frequency bucket.","shouldFailWhen":"This step should fail if repeated values are not accumulated.","roles":["frequency map","current value"],"mustProve":["The keyed state is incremented by key during the scan."],"mustNotAccept":["A write that replaces the count without reading the old count."]}},{"id":"init-best","title":"Start with no valid pair","description":"Initialize the best answer to 0 because a single distinct value is not harmonious.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Initializing the answer to 1","Returning a nonzero answer for all-equal arrays"],"hint":"No valid pair means answer 0.","semanticSpec":{"intent":"Initialize the numeric answer state.","doneWhen":"The best length starts at zero.","shouldFailWhen":"This step should fail if the answer starts at a positive value.","roles":["best length"],"mustProve":["The answer state is initialized to zero."],"mustNotAccept":["An answer initialized to one."]}},{"id":"check-neighbor","title":"Check the next value","description":"For each value `x`, check whether `x + 1` exists in the frequency map.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"checks_key_membership","scope":"check-adjacent-key-in-map","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Combining values with difference greater than one","Checking `x - 1` and `x + 1` then double counting"],"hint":"Treat the current value as the smaller value in the pair.","semanticSpec":{"intent":"Use keyed membership to find adjacent value buckets.","doneWhen":"The solution checks whether the frequency map contains a neighboring key.","shouldFailWhen":"This step should fail if no keyed membership check is used.","roles":["current value","neighbor value","frequency map"],"mustProve":["The algorithm checks an adjacent key derived from the current frequency-map key."],"mustNotAccept":["Combining counts without verifying the adjacent key exists."]}},{"id":"update-best","title":"Update the longest length","description":"When a neighbor exists, combine the two frequencies and keep the maximum.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Using only the larger bucket's count","Overwriting the best length with the last pair"],"hint":"The subsequence can include every occurrence of both adjacent values.","semanticSpec":{"intent":"Track the maximum combined adjacent frequency.","doneWhen":"The best answer is updated with an extremum comparison.","shouldFailWhen":"This step should fail if the best answer is not compared against candidate lengths.","roles":["candidate length","best length"],"mustProve":["The solution updates the numeric extremum state."],"mustNotAccept":["A plain assignment from the last candidate."]}},{"id":"return-best","title":"Return the best length","description":"Return the accumulated best harmonious subsequence length.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning the frequency map","Returning the count for the current value"],"hint":"The best accumulator is already 0 if no pair was found.","semanticSpec":{"intent":"Return the terminal accumulated answer.","doneWhen":"The final return is the best length after all keyed entries are checked.","shouldFailWhen":"This step should fail if a temporary count or map is returned.","roles":["best length","return value"],"mustProve":["The function returns the terminal accumulator."],"mustNotAccept":["Returning keyed state instead of the answer."]}}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","summary":"Tally the values once, then read each answer off neighboring counts.","workspacePanel":"code","body":["The work the brute force repeated was counting. Build counts in one pass and every pairing becomes a single addition, dropping O(n squared) to O(n).","The whole problem reduces to one rule: a harmonious pair is count[x] + count[x + 1], and only when x + 1 is actually present."],"takeaways":[{"title":"Order never mattered","body":"A subsequence keeps every copy of the two chosen values, so the length depends only on counts, not positions."},{"title":"The neighbor check is the algorithm","body":"Combine count[x] with count[x + 1] only when x + 1 exists; a lone bucket has a max-min difference of 0 and contributes nothing."},{"title":"Counting once beats recounting","body":"One tally pass turns each of n candidate pairs into an O(1) lookup, so the whole solution runs in O(n) time and O(n) space."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
