{"id":"h-index","title":"H-Index","difficulty":"medium","patterns":["sorting-linear"],"primaryConcept":"sorting-linear","concepts":["sorting-linear"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"citations","sizeMetric":"array-length","constraints":["non-negative"],"sizes":[8,16,32,64],"valueRange":{"min":0,"max":100}},"description":"Given an array `citations` where `citations[i]` is the number of citations for the `i`th paper, return the researcher's H-index.\n\nThe H-index is the largest integer `h` such that at least `h` papers have at least `h` citations each.\n\nFor this TraceCode exercise, solve it in linear time with counting buckets capped at `n`, where `n` is the number of papers. Do not sort the array.","requiredComplexity":[{"metric":"time","bound":"O(n)","scope":"function","functions":["hIndex"],"case":"worst","enforcement":"hard","reason":"The counting-bucket solution scans the citations once and then scans at most n bucket positions."}],"examples":[{"input":"citations = [3,0,6,1,5]","output":"3","explanation":"There are 3 papers with at least 3 citations: 3, 6, and 5. There are not 4 papers with at least 4 citations."},{"input":"citations = [1,3,1]","output":"1","explanation":"All three papers have at least 1 citation, but only one has at least 2, so the H-index is 1."}],"constraints":[{"id":"1-len-citations-5000","text":"1 <= len(citations) <= 5000","check":{"kind":"sizeRange","target":"citations","measure":"arrayLength","min":1,"max":5000}},{"id":"0-citations-i-1000","text":"0 <= citations[i] <= 1000","check":{"kind":"valueRange","target":"citations","selector":"arrayItems","min":0,"max":1000}}],"starterCode":"class Solution:\n    def hIndex(self, citations: list[int]) -> int:\n        # Your code here\n        pass","functionName":"hIndex","testCases":[{"id":"1","input":{"citations":[3,0,6,1,5]},"expected":3,"description":"Classic sample with three papers at or above three citations."},{"id":"2","input":{"citations":[1,3,1]},"expected":1,"description":"Every paper is cited, but only one has 2 or more, so h stops at 1."},{"id":"3","input":{"citations":[10,8,5,4,3]},"expected":4,"description":"Four papers have at least four citations."},{"id":"4","input":{"citations":[0]},"expected":0,"description":"A single uncited paper gives H-index 0."},{"id":"5","input":{"citations":[100,100,100]},"expected":3,"description":"Citation counts above n are capped into the n bucket."},{"id":"hidden-1","input":{"citations":[0,0,0,0]},"expected":0,"description":"All papers are uncited."},{"id":"hidden-2","input":{"citations":[4,4,0,0]},"expected":2,"description":"Two highly cited papers among four total papers."},{"id":"hidden-3","input":{"citations":[6,5,3,1,0]},"expected":3,"description":"The threshold lands exactly on the third paper."},{"id":"hidden-4","input":{"citations":[1,2,100]},"expected":2,"description":"A very large citation count should only contribute one paper."},{"id":"hidden-5","input":{"citations":[6,6,6,6,6,6]},"expected":6,"description":"Every paper supports the maximum possible H-index."},{"id":"topup-1","input":{"citations":[0,1,4,4,4]},"expected":3,"description":"Top-up case 1: three papers support h = 3 even though no paper has exactly three citations."},{"id":"topup-2","input":{"citations":[11,15,0,2,8,9,10]},"expected":5,"description":"Top-up case 2: large unsorted citation counts support a mid-range H-index."}],"hints":[{"level":1,"content":"The exact number of citations above n does not matter, because the H-index cannot exceed the number of papers."},{"level":2,"content":"Put each paper into a bucket for its citation count, but cap every citation count above n into bucket n."},{"level":3,"content":"Scan buckets from n down to 0 while accumulating how many papers have at least the current h citations. The first h where papers >= h is the answer.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"h-index-2026-11-20-count-per-score","approachSelection":{"contract":"approach-selection-v1","question":"How should the scores from 0 to n be tested?","decisionPrompt":"Pick the approach that settles every score while reading each paper a fixed number of times.","approaches":[{"id":"threshold-recount","name":"Recount the papers for every score","summary":"Test h from n down to 0, counting the papers with at least h citations each time.","decisionReason":"It returns the right score, but each test rereads all n papers, so a list whose answer is 0 costs about n × n reads.","complexity":{"time":"O(n²)","space":"O(1)"},"tradeoffs":["Needs no extra memory.","Reads every paper again for each score it tests."],"isOptimal":false},{"id":"counting-buckets","name":"One count per score, capped at n","summary":"Count the papers at each citation count from 0 to n, then test the scores from n down with one running count.","decisionReason":"One pass fills the n + 1 slots and one pass sweeps them. A count above n loses nothing in slot n, because no score above n is tested.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Uses n + 1 slots of extra memory.","Reads each paper once and each slot once."],"isOptimal":true},{"id":"uncapped-exact-buckets","name":"One count per citation count, uncapped","summary":"Keep a slot for every citation count up to the largest one, then sweep all of them.","decisionReason":"A single paper with 1,000 citations forces 1,001 slots, and no slot above n is needed to test a score.","complexity":{"time":"O(n + C)","space":"O(C)"},"tradeoffs":["Costs time and memory in proportion to the largest citation count C.","Capping at n returns the same scores with n + 1 slots."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-buckets","title":"Make a slot for every score","description":"Take n as the number of papers and create n + 1 counts, all starting at 0: one for each score from 0 to n.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Create a zero-filled bucket array sized for all thresholds from 0 through the number of papers.","doneWhen":"This step is done when the function derives n from the input length and initializes a mutable sequence with n + 1 zero slots.","shouldFailWhen":"This step should fail if the bucket structure is missing, has no extra n slot, or is not initialized before citation scanning begins.","roles":["paper count","bucket array","zero count slots"],"mustProve":["The code derives the paper count from the input.","The code allocates a zero-filled sequence that can represent thresholds 0 through n."],"mustNotAccept":["Sorting the citations instead of creating buckets.","Allocating only n slots and losing the capped n bucket."],"equivalentVariants":["Use a list of n + 1 zeroes.","Use any mutable indexed count structure with one slot for every threshold from 0 to n."],"proofSnippets":[{"id":"py-h-index-init-buckets","language":"python","code":"class Solution:\n    def hIndex(self, citations: list[int]) -> int:\n        n = len(citations)\n        buckets = [0] * (n + 1)\n        return 0"}]},"commonMistakes":["Making only n slots, which leaves no slot for a score of n."],"hint":"Scores run from 0 to n inclusive, which is n + 1 values. The last slot is where every paper with n or more citations gets counted."},{"id":"scan-citations","title":"Go through every paper","description":"Loop over the citation counts so that each paper is seen once.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Loop over the input citation counts so every paper contributes one count to the buckets.","doneWhen":"This step is done when the code has a direct scan over the citation array after bucket initialization.","shouldFailWhen":"This step should fail if the code only checks a subset of citations or skips the input scan entirely.","roles":["citations array","current citation","single pass"],"mustProve":["The code iterates over the citation input.","The scan variable represents each paper's citation count."],"mustNotAccept":["Hard-coding citation counts.","Scanning the bucket array before the citations have been counted."],"equivalentVariants":["Use a direct for-each citation loop.","Use an index-based loop that reads every citation."],"proofSnippets":[{"id":"py-h-index-scan-citations","language":"python","code":"class Solution:\n    def hIndex(self, citations: list[int]) -> int:\n        n = len(citations)\n        buckets = [0] * (n + 1)\n        for citation in citations:\n            capped = min(citation, n)\n        return 0"}]},"commonMistakes":[],"hint":"This pass reads the input list. The slots are read later, once every paper has been counted."},{"id":"fill-buckets","title":"Count each paper in its slot","description":"Add 1 to the slot for the paper's citation count, using slot n for any count above n.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"builds_projected_result_sequence","scope":"convert-index","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Convert each citation into a bounded bucket index and increment that bucket's count.","doneWhen":"This step is done when every citation writes exactly one increment into the bucket at min(citation, n) or an equivalent capped index.","shouldFailWhen":"This step should fail if large citation counts index past the bucket array, if counts overwrite instead of increment, or if the bucket write is not tied to the citation scan.","roles":["current citation","capped bucket index","bucket count update"],"mustProve":["The code derives a bucket index from the current citation and the paper count.","The code increments the bucket selected by that capped index."],"mustNotAccept":["Using citation counts greater than n as raw indexes.","Assigning a constant value to a bucket instead of adding one paper."],"equivalentVariants":["Use min(citation, n) as the bucket index.","Use an if branch that sends all citation counts above n into bucket n."],"proofSnippets":[{"id":"py-h-index-fill-buckets","language":"python","code":"class Solution:\n    def hIndex(self, citations: list[int]) -> int:\n        n = len(citations)\n        buckets = [0] * (n + 1)\n        for citation in citations:\n            capped = min(citation, n)\n            buckets[capped] += 1\n        return 0"}]},"commonMistakes":["Using a citation count above n as the slot number, which points past the last slot.","Setting the slot to 1 where it should grow by 1, which loses every later paper with the same count."],"hint":"A paper with 6 citations among five papers counts toward every score up to 5, the same as a paper with 5 citations."},{"id":"init-papers","title":"Start the running count at zero","description":"Before the sweep, create the count of papers with at least h citations, starting at 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_zero_accumulator","scope":"init-total","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Prepare a running total for papers whose citation counts are at least the threshold currently being tested.","doneWhen":"This step is done when the code creates a zero numeric accumulator after bucket counting and before the descending threshold scan.","shouldFailWhen":"This step should fail if the running total is missing, starts from a nonzero value, or is initialized inside the threshold loop.","roles":["running paper count","zero seed","threshold scan setup"],"mustProve":["The code initializes a numeric accumulator to zero.","The accumulator is available before the descending bucket scan begins."],"mustNotAccept":["Starting the paper count at n.","Resetting the running count during each threshold iteration."],"equivalentVariants":["Use a variable such as papers, total, or count initialized to 0.","Use any zero-seeded numeric state that is later increased by bucket counts."],"proofSnippets":[{"id":"py-h-index-init-papers","language":"python","code":"class Solution:\n    def hIndex(self, citations: list[int]) -> int:\n        n = len(citations)\n        buckets = [0] * (n + 1)\n        for citation in citations:\n            capped = min(citation, n)\n            buckets[capped] += 1\n        papers = 0\n        return 0"}]},"commonMistakes":["Resetting the count to 0 inside the sweep, which turns it back into the count for a single slot."],"hint":"The count is created once, outside the sweep, so that it keeps what the higher slots added."},{"id":"accumulate-papers","title":"Sweep h from n down to 0, adding each slot","description":"Step h from n down to 0, and at each h add that slot's count to the running count.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"additively_updates_accumulator","scope":"update-total","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Sweep possible H-index thresholds from high to low while accumulating all papers with at least that many citations.","doneWhen":"This step is done when the code scans bucket positions in descending order and adds each bucket count into the running paper total.","shouldFailWhen":"This step should fail if the scan moves upward, if it does not add bucket counts, or if it replaces the running total instead of accumulating.","roles":["descending threshold","bucket count","running paper count"],"mustProve":["The code traverses candidate thresholds from high toward low.","The running paper count increases by the bucket count at the current threshold."],"mustNotAccept":["Scanning only citation values that appeared in the input and skipping missing thresholds.","Using the current bucket alone instead of a cumulative count."],"equivalentVariants":["Use `range(n, -1, -1)` in Python.","Use a descending loop from n to 0 in any language."],"proofSnippets":[{"id":"py-h-index-accumulate-papers","language":"python","code":"class Solution:\n    def hIndex(self, citations: list[int]) -> int:\n        n = len(citations)\n        buckets = [0] * (n + 1)\n        for citation in citations:\n            capped = min(citation, n)\n            buckets[capped] += 1\n        papers = 0\n        for h in range(n, -1, -1):\n            papers += buckets[h]\n        return 0"}]},"commonMistakes":["Sweeping upward from 0. The running count would then hold the papers with at most h citations, which is the wrong group.","Replacing the running count with the slot's count. Papers in higher slots also have at least h citations."],"hint":"After the addition at h, the running count is the number of papers with at least h citations."},{"id":"return-h","title":"Return the first h the count reaches","description":"Inside the sweep, return h as soon as the running count is at least h.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_scan_decision","scope":"return-decision","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Stop at the largest threshold whose cumulative paper count reaches the threshold value.","doneWhen":"This step is done when the descending scan checks whether the running paper count is at least h and immediately returns h on the first true threshold.","shouldFailWhen":"This step should fail if the code returns the paper count instead of h, keeps scanning after finding a valid threshold, or uses a strict greater-than comparison.","roles":["running paper count","current threshold","threshold return"],"mustProve":["The code compares the cumulative paper count against the current threshold.","The code returns the current threshold from that branch."],"mustNotAccept":["Returning the cumulative paper count.","Returning a constant after the scan without checking the threshold."],"equivalentVariants":["Use `if papers >= h: return h`.","Use any equivalent branch that returns the current descending threshold when the cumulative count reaches it."],"proofSnippets":[{"id":"py-h-index-return-h","language":"python","code":"class Solution:\n    def hIndex(self, citations: list[int]) -> int:\n        n = len(citations)\n        buckets = [0] * (n + 1)\n        for citation in citations:\n            capped = min(citation, n)\n            buckets[capped] += 1\n        papers = 0\n        for h in range(n, -1, -1):\n            papers += buckets[h]\n            if papers >= h:\n                return h\n        return 0"}]},"commonMistakes":["Returning the running count. It can be larger than h when one slot adds several papers.","Requiring the count to be greater than h. Three papers with at least 3 citations do earn a score of 3."],"hint":"The sweep runs from the highest score down, so the first h that passes is the largest one that passes."}],"slides":[{"id":"read-the-signal","kind":"info","title":"One score from a list of citation counts","workspacePanel":"problem","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"five-papers","state":{"nums":[3,0,6,1,5],"labels":{"nums":"citations"}}}]},"body":["A researcher has written some papers, and each paper has a citation count: the number of times other papers refer to it. The panel shows one researcher's five papers.","The H-index turns that list into a single score. A score of h is earned when at least h papers have h or more citations each. For example, a score of 2 takes two papers with 2 or more citations.","The function receives the citation counts and returns the highest score the researcher earns."]},{"id":"score-by-hand","kind":"case-probe","title":"What is the H-index of these five papers?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"five-papers","state":{"nums":[3,0,6,1,5],"labels":{"nums":"citations"}}}]},"options":[{"id":"two","label":"2","rationale":"A score of 2 is earned, because three papers have 2 or more citations. A higher score is earned as well, and the H-index is the highest one.","isCorrect":false},{"id":"three","label":"3","rationale":"Three papers have 3 or more citations: the ones with 3, 6 and 5. A score of 4 fails, because only two papers have 4 or more.","isCorrect":true},{"id":"four","label":"4","rationale":"A score of 4 takes four papers with 4 or more citations. Only the papers with 6 and 5 qualify.","isCorrect":false},{"id":"six","label":"6","rationale":"6 is the highest citation count on the list, but a score of 6 takes six papers with 6 or more citations. One paper has that many.","isCorrect":false}]},{"id":"score-limit","kind":"case-probe","title":"What is the highest score any five papers could earn?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"five-papers","state":{"nums":[3,0,6,1,5],"labels":{"nums":"citations"}}}]},"options":[{"id":"six","label":"6, the highest citation count here","rationale":"The paper with 6 citations is one paper. A score of 6 takes six papers that each have 6 or more.","isCorrect":false},{"id":"five","label":"5, the number of papers","rationale":"A score of 6 takes six papers, and there are five. A score of 5 is possible when all five papers have 5 or more citations. So with n papers, the H-index is a whole number from 0 to n.","isCorrect":true},{"id":"no-limit","label":"No limit, since citations can keep growing","rationale":"More citations on the same five papers never add a sixth paper, and a score of 6 takes six.","isCorrect":false}]},{"id":"brute-force","kind":"code-trace","title":"Test every score, highest first","workspacePanel":"trace","body":["This loop checks scores the way you did by hand. It tries each h from 5, the highest possible score, down to 0. For each one it counts the papers with at least h citations, and it returns the first h whose count reaches h."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"for h in range(len(citations), -1, -1):\n    count = 0\n    for c in citations:\n        if c >= h:\n            count += 1\n    if count >= h:\n        return h","steps":[{"id":"try-five","title":"h = 5: two papers pass","codeLine":4,"summary":"The inner loop reads all five papers. Only the 6 and the 5 are at least 5, so `count` ends at 2.","state":{"nums":[3,0,6,1,5],"h":5,"count":2,"labels":{"nums":"citations"}}},{"id":"five-fails","title":"A count of 2 does not reach 5","codeLine":6,"summary":"`count >= h` is false, so the outer loop moves down to h = 4.","state":{"nums":[3,0,6,1,5],"h":5,"count":2,"labels":{"nums":"citations"}}},{"id":"try-four","title":"h = 4: the same five papers, read again","codeLine":4,"summary":"`count` starts over at 0. The 6 and the 5 pass again, and 2 is less than 4.","state":{"nums":[3,0,6,1,5],"h":4,"count":2,"labels":{"nums":"citations"}}},{"id":"try-three","title":"h = 3: a third full pass","codeLine":4,"summary":"This time the paper with 3 citations passes as well, so `count` reaches 3.","state":{"nums":[3,0,6,1,5],"h":3,"count":3,"labels":{"nums":"citations"}}},{"id":"return-three","title":"3 reaches 3, so the loop returns 3","codeLine":7,"summary":"Scores 2, 1 and 0 are never tested, because each one is lower than a score that already passed.","state":{"nums":[3,0,6,1,5],"h":3,"count":3,"labels":{"nums":"citations"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"for (let h = citations.length; h >= 0; h--) {\n    let count = 0;\n    for (const c of citations) {\n        if (c >= h) {\n            count++;\n        }\n    }\n    if (count >= h) {\n        return h;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9},"statementBundles":{"5":{"startLine":5,"endLine":7},"7":{"startLine":9,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"for (let h = citations.length; h >= 0; h--) {\n    let count = 0;\n    for (const c of citations) {\n        if (c >= h) {\n            count++;\n        }\n    }\n    if (count >= h) {\n        return h;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9},"statementBundles":{"5":{"startLine":5,"endLine":7},"7":{"startLine":9,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"for (int h = citations.size(); h >= 0; h--) {\n    int count = 0;\n    for (Integer c : citations) {\n        if (c >= h) {\n            count++;\n        }\n    }\n    if (count >= h) {\n        return h;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9},"statementBundles":{"5":{"startLine":5,"endLine":7},"7":{"startLine":9,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"for (int h = citations.Count; h >= 0; h--) {\n    int count = 0;\n    foreach (int c in citations) {\n        if (c >= h) {\n            count++;\n        }\n    }\n    if (count >= h) {\n        return h;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9},"statementBundles":{"5":{"startLine":5,"endLine":7},"7":{"startLine":9,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"for (int h = citations.size(); h >= 0; h--) {\n    int count = 0;\n    for (int c : citations) {\n        if (c >= h) {\n            count++;\n        }\n    }\n    if (count >= h) {\n        return h;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9},"statementBundles":{"5":{"startLine":5,"endLine":7},"7":{"startLine":9,"endLine":11}}}}}},{"id":"waste-probe","kind":"case-probe","title":"With n papers, about how many citation counts could this loop read?","workspacePanel":"trace","options":[{"id":"n-reads","label":"About n: each paper is read once","rationale":"Every new score restarts the inner loop. In the trace each paper was read three times, once for each score tested.","isCorrect":false},{"id":"three-n","label":"About 3n: it stops at the third score","rationale":"It stopped at the third score because this answer was 3 out of a possible 5. When the answer is 0 or 1, nearly every score gets a full pass first.","isCorrect":false},{"id":"n-squared","label":"About n × n: up to n + 1 scores, n papers each","rationale":"The loop can test every score from n down to 0, and each test reads all n papers. That happens whenever the answer turns out to be 0. With 5,000 papers, the most this problem allows, that is about 25 million reads.","isCorrect":true}]},{"id":"repeat-probe","kind":"case-probe","title":"`count` was 2 at h = 4 and 3 at h = 3. Which paper made the difference?","workspacePanel":"trace","options":[{"id":"top-two","label":"The papers with 6 and 5 citations","rationale":"Those two were already counted at h = 4. Reading them again at h = 3 gave the same result.","isCorrect":false},{"id":"exact-three","label":"The paper with exactly 3 citations","rationale":"The 6 and the 5 passed at h = 4, so they pass at h = 3 too. The paper with 3 citations is the only one that fails 4 and passes 3. Each step down from h + 1 to h adds only the papers with exactly h citations.","isCorrect":true},{"id":"low-two","label":"The papers with 0 and 1 citations","rationale":"Neither one reaches 3, so neither is counted at h = 3.","isCorrect":false}]},{"id":"state-probe","kind":"case-probe","title":"What could one pass over the papers record, so that each step down is a single addition?","workspacePanel":"trace","options":[{"id":"per-count","label":"How many papers have each citation count","rationale":"With those numbers recorded, the step from h = 4 to h = 3 is 2 + 1: the old count plus the one paper with exactly 3 citations. No paper is read again.","isCorrect":true},{"id":"sum","label":"The sum of all the citation counts","rationale":"The sum here is 15, and it would still be 15 if a single paper had all 15 citations. It cannot say how many papers reach 3.","isCorrect":false},{"id":"max","label":"The highest citation count","rationale":"Knowing that the top paper has 6 citations does not say how many papers have 3 or more.","isCorrect":false}]},{"id":"tally-start","kind":"info","title":"One slot for each score the loop tests","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty","title":"Six slots, numbered 0 to 5, all starting at 0","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5]},{"name":"buckets","values":[0,0,0,0,0,0]}]}},{"id":"place-three","title":"The paper with 3 citations adds 1 to slot 3","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5],"i":0,"labels":{"i":"citation"}},{"name":"buckets","values":[0,0,0,1,0,0],"current":3}]}},{"id":"place-zero","title":"The paper with 0 citations adds 1 to slot 0","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5],"i":1,"labels":{"i":"citation"}},{"name":"buckets","values":[1,0,0,1,0,0],"current":0}]}}]},"body":["Call that record `buckets`. It has one slot for each score the loop tests. For a count c below 5, `buckets[c]` is the number of papers with exactly c citations.","The loop only tests h from 5 down to 0, so `buckets` needs six slots, numbered 0 to 5. A single pass over the papers fills them, adding 1 to one slot for each paper."]},{"id":"cap-probe","kind":"case-probe","title":"The next paper has 6 citations, and the slots stop at 5. Where should it be counted?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"six-arrives","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5],"i":2,"labels":{"i":"citation"}},{"name":"buckets","values":[1,0,0,1,0,0]}]}}]},"options":[{"id":"new-slot","label":"In a new slot 6","rationale":"The loop starts at h = 5, so a slot 6 would never be added in and the paper would be missed. Starting the loop higher would take a slot for every citation count up to the largest one.","isCorrect":false},{"id":"slot-five","label":"In slot 5","rationale":"Every score the loop tests is 5 or lower, and a paper with 6 citations counts toward each of them, exactly as a paper with 5 citations does. Slot 5 now means 5 or more.","isCorrect":true},{"id":"left-out","label":"Nowhere: it is left out","rationale":"It has more than 3 citations, so it has to be counted when h = 3 is tested. Without it that count would be 2, and a score of 3 would fail.","isCorrect":false}]},{"id":"tally-finish","kind":"info","title":"Three more papers and `buckets` is complete","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"place-six","title":"6 is above 5, so the paper goes in slot 5","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5],"i":2,"labels":{"i":"citation"}},{"name":"buckets","values":[1,0,0,1,0,1],"current":5}]}},{"id":"place-one","title":"The paper with 1 citation adds 1 to slot 1","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5],"i":3,"labels":{"i":"citation"}},{"name":"buckets","values":[1,1,0,1,0,1],"current":1}]}},{"id":"place-five","title":"The paper with 5 citations joins it in slot 5","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5],"i":4,"labels":{"i":"citation"}},{"name":"buckets","values":[1,1,0,1,0,2],"current":5}]}}]},"body":["Each paper goes in the slot for its citation count or for n, the number of papers, whichever is smaller. After this pass every paper sits in exactly one slot, and the citation counts are never read again."]},{"id":"dry-run-setup","kind":"info","title":"The score loop again, reading slots in place of papers","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sweep-start","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5]},{"name":"buckets","values":[1,1,0,1,0,2],"i":5,"labels":{"i":"h"}}],"papers":0}}]},"body":["The loop that tests scores keeps its shape: h still runs from 5 down to 0, one sweep across the slots.","Only the counting changes. A running count, `papers`, starts at 0. At each h the loop adds `buckets[h]` to it, then checks whether `papers` has reached h."]},{"id":"trace","kind":"dry-run","source":"trace-example","title":"The sweep on the five papers","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5]},{"name":"buckets","values":[1,1,0,1,0,2],"i":5,"labels":{"i":"h"}}],"papers":0}},{"id":"h-five","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5]},{"name":"buckets","values":[1,1,0,1,0,2],"i":5,"labels":{"i":"h"}}],"papers":2}},{"id":"h-four","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5]},{"name":"buckets","values":[1,1,0,1,0,2],"i":4,"labels":{"i":"h"}}],"papers":2}},{"id":"h-three","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5]},{"name":"buckets","values":[1,1,0,1,0,2],"i":3,"labels":{"i":"h"}}],"papers":3}}]},"beats":[{"id":"h-five","title":"Slot 5 is added to `papers`. Does a score of 5 pass?","options":[{"id":"no-one","label":"No: it becomes 1, the one paper with exactly 5","rationale":"Slot 5 also holds the paper with 6 citations, because every count above 5 was put there. The count becomes 2.","isCorrect":false},{"id":"no-two","label":"No: it becomes 2, which is short of 5","rationale":"Slot 5 holds the two papers with 5 or more citations, and a score of 5 takes five.","isCorrect":true},{"id":"yes-two","label":"Yes: it becomes 2, and both have 5 or more","rationale":"Both papers do have 5 or more citations, but a score of 5 is earned only when five papers do.","isCorrect":false}]},{"id":"h-four","title":"h drops to 4, where the slot is empty. What is `papers` now?","options":[{"id":"zero","label":"0, because slot 4 is empty","rationale":"No paper has exactly 4 citations, but the two papers from slot 5 have at least 4. They stay in the count.","isCorrect":false},{"id":"still-two","label":"2, the same as before","rationale":"Adding an empty slot changes nothing, and the two papers with 5 or more citations also have 4 or more.","isCorrect":true},{"id":"four","label":"4, to match h","rationale":"The running count changes only by what a slot adds. h is the number it gets compared to.","isCorrect":false}]},{"id":"h-three","title":"h drops to 3, and slot 3 adds 1. What does the loop do?","options":[{"id":"next","label":"Moves on to h = 2 to look for a better score","rationale":"Any score found below 3 is smaller than 3. The loop runs from the top so that the first score to pass is the best one.","isCorrect":false},{"id":"fail","label":"Fails 3, because slot 3 holds one paper","rationale":"The check uses `papers`, which is now 3. Slot 3 is only the newest part of that count.","isCorrect":false},{"id":"return","label":"Returns 3, because `papers` is now 3","rationale":"The papers with 6, 5 and 3 citations are in the count, and three papers are enough for a score of 3. Scores 5 and 4 already failed.","isCorrect":true}]}]},{"id":"edge-case-intro","kind":"info","title":"The sweep found the same 3 and read each paper once. Next, three other lists.","ctaLabel":"Try the three lists","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sweep-end","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5]},{"name":"buckets","values":[1,1,0,1,0,2],"i":3,"labels":{"i":"h"}}],"papers":3}}]},"body":["In the first list, no paper has a citation. In the second, every paper has far more citations than there are papers. In the third, one slot adds most of the papers at once.","Does the same sweep return the right score on each one?"]},{"id":"all-zero-edge","kind":"case-probe","title":"In the first list, no paper has a citation. Which score does the loop return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-zero","state":{"arrays":[{"name":"citations","values":[0,0,0]},{"name":"buckets","values":[3,0,0,0],"i":3,"labels":{"i":"h"}}],"papers":0}}]},"options":[{"id":"three","label":"3, because slot 0 holds three papers","rationale":"Slot 0 does hold all three papers, but they are added when h is 0, and the value returned is h.","isCorrect":false},{"id":"zero","label":"0, when h reaches slot 0","rationale":"`papers` is still 0 at h = 3, 2 and 1, so none of those pass. At h = 0 it becomes 3, and 3 is at least 0. A score of 0 passes on any list, so the loop always returns a score.","isCorrect":true},{"id":"none","label":"Nothing: no score ever passes","rationale":"A score of 0 always passes, because `papers` is never below 0. The loop gets there as long as it runs all the way down to h = 0.","isCorrect":false}]},{"id":"all-high-edge","kind":"case-probe","title":"In the second list, each of three papers has 100 citations. Which score does the loop return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-high","state":{"arrays":[{"name":"citations","values":[100,100,100]},{"name":"buckets","values":[0,0,0,3],"i":3,"labels":{"i":"h"}}],"papers":0}}]},"options":[{"id":"three","label":"3, at its first step","rationale":"All three papers were counted in slot 3, the last slot. At h = 3 `papers` becomes 3, which reaches 3.","isCorrect":true},{"id":"hundred","label":"100, the count they all share","rationale":"A score of 100 takes 100 papers. With three papers the slots stop at 3, and so do the scores.","isCorrect":false},{"id":"zero","label":"0, because slots 0 to 2 are empty","rationale":"The loop starts at slot 3 and returns there. It never reaches the empty slots.","isCorrect":false}]},{"id":"jump-edge","kind":"case-probe","title":"In the third list, `papers` jumps from 1 to 3 at h = 1. What does the loop return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"jump","state":{"arrays":[{"name":"citations","values":[1,3,1]},{"name":"buckets","values":[0,2,0,1],"i":1,"labels":{"i":"h"}}],"papers":3}}]},"options":[{"id":"one","label":"1","rationale":"The check passes at h = 1, and the loop returns h. Only one paper has 2 or more citations, so no higher score was possible. `papers` never equaled h at any check, which is why the check is `papers >= h`.","isCorrect":true},{"id":"two","label":"2","rationale":"h = 2 was tested one step earlier, when the count was 1, and 1 is less than 2.","isCorrect":false},{"id":"three","label":"3","rationale":"3 is the running count, the number of papers with at least 1 citation. The score is the h being tested when the count first reaches it.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"One pass to count and one sweep to score. Now write the function.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sweep-end","state":{"arrays":[{"name":"citations","values":[3,0,6,1,5]},{"name":"buckets","values":[1,1,0,1,0,2],"i":3,"labels":{"i":"h"}}],"papers":3}}]},"body":["The function makes n + 1 slots, one for each score from 0 to n, all starting at 0. Here n is the number of papers.","It reads each paper once and adds 1 to that paper's slot. A paper with more than n citations goes in slot n.","Then it steps h from n down to 0 and adds each slot to a running count of papers. It returns the first h that the running count reaches."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Build the slots, then sweep them","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"H-index from one count per score and one sweep","workspacePanel":"code","takeaways":[{"title":"A score of h takes h papers","body":"With n papers the H-index is one of the n + 1 values from 0 to n, so those are the only scores worth testing."},{"title":"Count papers by citation count, capped at n","body":"Below n, `buckets[c]` is the number of papers with exactly c citations. Slot n holds every paper with n or more, because a paper with more than n citations counts toward every score that is tested."},{"title":"One running count, from the top down","body":"Stepping from h + 1 to h adds only `buckets[h]`. So at every test, `papers` is the number of papers with at least h citations, and the first h it reaches is the highest."},{"title":"O(n) time and O(n) space","body":"One pass over the n papers fills the slots, and one pass over the n + 1 slots tests the scores. Retesting each score from scratch took about n × n reads. The slots are the extra memory. Sorting the papers first would also work, at O(n log n) time."}]}],"slidesOrigin":"authored"}}
