Skip to content

Conversation

@vikahaze
Copy link
Collaborator

@vikahaze vikahaze commented Dec 9, 2025

Summary

This PR adds solutions and explanations for 10 LeetCode problems that have been verified as accepted.

Problems Added

  • 3583: Count Special Triplets - O(N) solution using frequency maps
  • 3772: Maximum Subgraph Score in a Tree - O(N) rerooting DP solution
  • 3771: Total Score of Dungeon Runs - O(N log N) solution using prefix sums and binary search
  • 3770: Largest Prime from Consecutive Prime Sum - Sieve of Eratosthenes solution
  • 3766: Minimum Operations to Make Binary Palindrome - O(N log P) solution using binary search
  • 3768: Minimum Inversion Count in Subarrays of Fixed Length - Fenwick Tree solution
  • 3767: Maximize Points After Choosing K Tasks - Greedy solution with delta sorting
  • 3765: Complete Prime Number - Prime checking solution
  • 3761: Minimum Absolute Distance Between Mirror Pairs - Hash map solution
  • 3760: Maximum Substrings With Distinct Start - Simple distinct character count

Notes

  • All solutions have been verified as accepted on LeetCode
  • Problems 3762 and 3769 were removed due to submission failures (TLE and session expired)
  • All explanations follow the structured format defined in the workspace rules

Summary by Sourcery

Add and update LeetCode solutions and explanations, including new content for problem 3583 and corrections for problems 3760, 3761, 3771, 3772, 3766, and 3770, plus documentation for problem 1431 across book sets.

New Features:

  • Introduce a solution and detailed explanation for problem 3583 (Count Special Triplets) using frequency maps.
  • Add problem 1431 (Kids With the Greatest Number of Candies) description, explanation, and sample solution across the main, LeetCode 75, and visualization book collections.

Bug Fixes:

  • Correct the solution and explanation for problem 3760 to match the distinct-start-substrings formulation.
  • Replace the problem 3761 solution and explanation with the mirror-pair distance implementation using digit reversal and a hash map.
  • Fix problem 3772 by switching from per-root recomputation to a linear-time rerooting DP and aligning the explanation with the optimized approach.
  • Optimize and correct problem 3771 by using prefix sums with binary search and updating the explanation accordingly.

Enhancements:

  • Improve the problem 3766 solution by replacing the linear scan over palindromes with binary search on a precomputed list.
  • Tighten the problem 3770 implementation to only consider consecutive prime sums starting from 2, avoiding unnecessary recomputation.

Summary by CodeRabbit

  • New Features

    • Added LeetCode problem 1431 (Kids With the Greatest Number of Candies) across books and visualization materials.
  • Documentation

    • Added or revised explanations for problems 3583, 3760, 3761, 3771, 3772.
    • Removed explanations for problems 3762 and 3769.
  • Chores

    • Updated the All problem set ordering and membership in book-sets.json.

✏️ Tip: You can customize this high-level summary in your review settings.


Note

Adds a new solution for 3583, refactors/optimizes solutions and explanations for 3760/3761/3771/3772/3770/3766, removes 3762/3769, and adds 1431 content across books.

  • Solutions:
    • Add solutions/3583/01.py (freq maps, O(n)).
    • Replace solutions/3760/01.py with distinct-char count approach.
    • Replace solutions/3761/01.py with mirror-pair distance via hash map.
    • Optimize solutions/3766/01.py using binary search over precomputed palindromes.
    • Tighten solutions/3770/01.py to consecutive prime sums from 2 only.
    • Rework solutions/3771/01.py to prefix sums + binary search (O(n log n)).
    • Rewrite solutions/3772/01.py to rerooting DP (O(n)).
    • Remove solutions/3762/01.py, solutions/3769/01.py.
  • Explanations:
    • Add/align explanations/3583/en.md, explanations/3760/en.md, explanations/3761/en.md, explanations/3771/en.md, explanations/3772/en.md with updated strategies.
    • Remove obsolete explanations/3762/en.md, explanations/3769/en.md.
  • Docs (Books):
    • Add problem 1431 (description, hint, solution) to books/All.md, books/LeetCode_75.md, books/Visualization.md.
  • Config:
    • Minor adjustments to data/book-sets.json problem listings.

Written by Cursor Bugbot for commit cb2768e. This will update automatically on new commits. Configure here.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Dec 9, 2025

🧙 Sourcery is reviewing your pull request!


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link

coderabbitai bot commented Dec 9, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Added new problem 1431 entries to multiple docs, modified the All problem ID list, added new solution/explanation for 3583, rewrote or removed implementations and explanations for several problems in the 3760–3772 range (mix of simplifications, optimizations, rerooting DP, and deletions).

Changes

Cohort / File(s) Change Summary
Docs: Problem 1431
books/All.md, books/LeetCode_75.md, books/Visualization.md
Added "1431. Kids With the Greatest Number of Candies [Easy]" entry (description, constraints, hint, Python solution). Entry appears duplicated in some files.
Data: book sets
data/book-sets.json
Reworked trailing IDs in the All list: reordered/trimmed a contiguous tail of problem IDs (some IDs removed, others retained/reordered). Other book-set sections unchanged structurally.
New solution + explanation (3583)
solutions/3583/01.py, explanations/3583/en.md
Added solution counting special triplets using two frequency maps (freq_before/freq_after) with O(n) pass; added detailed explanation and step-by-step walkthrough.
API/impl replaced (3760)
solutions/3760/01.py, explanations/3760/en.md
Replaced graph/DP minimumCost implementation with maxDistinct(self, s: str) -> int returning distinct character count; explanation updated to reflect new simple approach.
API/impl replaced (3761)
solutions/3761/01.py, explanations/3761/en.md
Replaced tree/DP countPaths with minMirrorPairDistance(self, nums: List[int]) -> int; single-pass hash-map using reversed numbers to compute minimal mirror distance; explanation updated.
Removal (3762)
solutions/3762/01.py, explanations/3762/en.md
Deleted minOperations implementation and its explanatory document.
Optimization (3766)
solutions/3766/01.py
Replaced brute-force palindrome scan with binary search (bisect_left) against precomputed palindromes; method signature unchanged.
Removal (3769)
solutions/3769/01.py, explanations/3769/en.md
Deleted sortByReflection solution and its explanatory document.
Simplification (3770)
solutions/3770/01.py
Simplified consecutive-prime-sum search to a forward running-sum approach; added early edge-case handling; signature unchanged.
Optimization (3771)
solutions/3771/01.py, explanations/3771/en.md
Replaced O(n²) nested loops with O(n log n) approach using prefix sums and binary search (bisect_left); explanation updated.
Refactor (3772)
solutions/3772/01.py, explanations/3772/en.md
Refactored to two-pass rerooting DP: compute down[node] via dfs1 and propagate ans[node] via dfs2; maintained O(n) complexity; explanation updated.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Files needing focused review:
    • solutions/3761/01.py — verify reverse-digit helper, indexing, and min-distance update logic.
    • solutions/3772/01.py — validate dfs1/dfs2 rerooting formulas, parent-contribution math, and edge cases.
    • solutions/3583/01.py — check freq_before/freq_after initialization and modulo arithmetic.
    • solutions/3771/01.py — confirm prefix sum thresholds and bisect boundary handling.
    • data/book-sets.json — ensure no unintended removals/duplicates and consistent membership across sets.

Possibly related PRs

Poem

🐰 Hooray, I hop with joyful bounds,

I counted triplets, checked palindromic rounds,
I rerooted trees and mirrored eyes,
Trimmed lists and optimized the tries,
A carrot for code — swift, clean, and sound!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding solutions and explanations for 10 LeetCode problems (3583, 3772, 3771, 3770, 3766, 3768, 3767, 3765, 3761, 3760).

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3089bef and cb2768e.

📒 Files selected for processing (1)
  • data/book-sets.json (1 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @vikahaze, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🧹 Nitpick comments (5)
solutions/3766/01.py (1)

16-26: Move bisect import out of the per‑element loop; verify bounds vs. constraints

The binary‑search logic for picking the nearest palindrome via bisect_left looks correct, and the two neighbor checks (at idx and idx - 1) are sufficient.

Two small follow‑ups:

  1. import bisect inside for num in nums: runs on every iteration. Python caches modules so it won’t re-import from disk, but it still does unnecessary lookups. Prefer importing once at module or function scope:
+import bisect
+
 class Solution:
     def minOperations(self, nums: List[int]) -> List[int]:
@@
-        for num in nums:
-            # Use binary search to find closest palindrome
-            import bisect
-            idx = bisect.bisect_left(palindromes, num)
+        for num in nums:
+            # Use binary search to find closest palindrome
+            idx = bisect.bisect_left(palindromes, num)
  1. The approach assumes the nearest valid target always lies among palindromes in 1..5000. That’s consistent with the contest write‑ups, but it would be good to double‑check against the official constraints (e.g., whether nums[i] can be 0 or exceed 5000) and maybe add a short comment explaining why 5000 is a safe upper bound here so future readers don’t have to re-derive it.
books/All.md (2)

8932-8933: Fix bare URL style to satisfy markdown linting.

Wrap the URL in angle brackets (or make it a markdown link) to silence MD034.

-https://leetcode.com/problems/kids-with-the-greatest-number-of-candies
+<https://leetcode.com/problems/kids-with-the-greatest-number-of-candies>

8941-8941: Use proper headings instead of bold labels.

Replace emphasized labels with headings to address MD036 and improve structure.

-**Examples**
+### Examples
@@
-**Constraints**
+### Constraints

Also applies to: 8960-8960

solutions/3770/01.py (1)

18-28: Remove redundant condition on Line 27.

The condition current_sum <= n on Line 27 is redundant because the loop breaks on Line 25 when current_sum > n. Any value reaching Line 27 is guaranteed to be <= n.

Apply this diff:

             current_sum += primes[i]
             if current_sum > n:
                 break
             # Check if sum is prime and <= n
-            if current_sum <= n and is_prime[current_sum]:
+            if is_prime[current_sum]:
                 res = max(res, current_sum)
solutions/3772/01.py (1)

5-6: Move import to module level.

The from collections import defaultdict import inside the method works but is unconventional. Module-level imports are preferred for clarity and slight performance benefit (import happens once at module load).

+from collections import defaultdict
+from typing import List
+
 class Solution:
     def maxSubgraphScore(
         self, n: int, edges: List[List[int]], good: List[int]
     ) -> List[int]:
         # Build tree
-        from collections import defaultdict
-
         graph = defaultdict(list)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fec1102 and 3089bef.

📒 Files selected for processing (20)
  • books/All.md (1 hunks)
  • books/LeetCode_75.md (1 hunks)
  • books/Visualization.md (1 hunks)
  • data/book-sets.json (2 hunks)
  • explanations/3583/en.md (1 hunks)
  • explanations/3760/en.md (1 hunks)
  • explanations/3761/en.md (1 hunks)
  • explanations/3762/en.md (0 hunks)
  • explanations/3769/en.md (0 hunks)
  • explanations/3771/en.md (1 hunks)
  • explanations/3772/en.md (2 hunks)
  • solutions/3583/01.py (1 hunks)
  • solutions/3760/01.py (1 hunks)
  • solutions/3761/01.py (1 hunks)
  • solutions/3762/01.py (0 hunks)
  • solutions/3766/01.py (1 hunks)
  • solutions/3769/01.py (0 hunks)
  • solutions/3770/01.py (1 hunks)
  • solutions/3771/01.py (1 hunks)
  • solutions/3772/01.py (1 hunks)
💤 Files with no reviewable changes (4)
  • explanations/3769/en.md
  • solutions/3762/01.py
  • explanations/3762/en.md
  • solutions/3769/01.py
🧰 Additional context used
🧬 Code graph analysis (1)
solutions/3770/01.py (1)
solutions/3765/01.py (1)
  • is_prime (3-13)
🪛 LanguageTool
books/LeetCode_75.md

[style] ~520-~520: The word ‘Greatest’ tends to be overused in this context. Consider an alternative.
Context: ... len(count) ``` ## 1431. Kids With the Greatest Number of Candies [Easy] https://leetcode.com/...

(A_GREAT_NUMBER)


[style] ~525-~525: The word ‘Greatest’ tends to be overused in this context. Consider an alternative.
Context: ...### Explanation ## 1431. Kids With the Greatest Number of Candies [Easy] https://leetcode.com...

(A_GREAT_NUMBER)


[style] ~532-~532: The word ‘greatest’ tends to be overused in this context. Consider an alternative.
Context: ... the extraCandies, they will have the greatest number of candies among all the kids, or false...

(A_GREAT_NUMBER)


[style] ~534-~534: The word ‘greatest’ tends to be overused in this context. Consider an alternative.
Context: .... Note that multiple kids can have the greatest number of candies. Examples ```text Inpu...

(A_GREAT_NUMBER)

explanations/3771/en.md

[style] ~11-~11: As an alternative to the over-used intensifier ‘very’, consider replacing this phrase.
Context: ...efix sums - Edge Case: If damage is very large, HP may become negative quickly **1.2 ...

(EN_WEAK_ADJECTIVE)

books/Visualization.md

[style] ~89-~89: The word ‘Greatest’ tends to be overused in this context. Consider an alternative.
Context: ...next = next ``` ## 1431. Kids With the Greatest Number of Candies [Easy] https://leetcode.com/...

(A_GREAT_NUMBER)


[style] ~94-~94: The word ‘Greatest’ tends to be overused in this context. Consider an alternative.
Context: ...### Explanation ## 1431. Kids With the Greatest Number of Candies [Easy] https://leetcode.com...

(A_GREAT_NUMBER)


[style] ~101-~101: The word ‘greatest’ tends to be overused in this context. Consider an alternative.
Context: ... the extraCandies, they will have the greatest number of candies among all the kids, or false...

(A_GREAT_NUMBER)


[style] ~103-~103: The word ‘greatest’ tends to be overused in this context. Consider an alternative.
Context: .... Note that multiple kids can have the greatest number of candies. Examples ```text Inpu...

(A_GREAT_NUMBER)

🪛 markdownlint-cli2 (0.18.1)
books/All.md

8926-8926: Bare URL used

(MD034, no-bare-urls)


8930-8930: Multiple headings with the same content

(MD024, no-duplicate-heading)


8932-8932: Bare URL used

(MD034, no-bare-urls)


8934-8934: Multiple headings with the same content

(MD024, no-duplicate-heading)


8941-8941: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


8960-8960: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


8969-8969: Multiple headings with the same content

(MD024, no-duplicate-heading)


8972-8972: Multiple headings with the same content

(MD024, no-duplicate-heading)

books/Visualization.md

90-90: Bare URL used

(MD034, no-bare-urls)


94-94: Multiple headings with the same content

(MD024, no-duplicate-heading)


96-96: Bare URL used

(MD034, no-bare-urls)


105-105: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


124-124: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


133-133: Multiple headings with the same content

(MD024, no-duplicate-heading)


136-136: Multiple headings with the same content

(MD024, no-duplicate-heading)

🪛 Ruff (0.14.8)
solutions/3761/01.py

2-2: Undefined name List

(F821)

solutions/3583/01.py

2-2: Undefined name List

(F821)

solutions/3772/01.py

3-3: Undefined name List

(F821)


3-3: Undefined name List

(F821)


3-3: Undefined name List

(F821)


4-4: Undefined name List

(F821)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (20)
solutions/3771/01.py (1)

18-24: LGTM! Efficient binary search implementation.

The optimization from O(n²) to O(n log n) using prefix sums and binary search is well-implemented. The algorithm correctly counts valid starting positions for each room by finding the first index where the accumulated damage allows meeting the requirement.

solutions/3770/01.py (1)

15-16: LGTM! Good edge case handling.

The check for an empty primes list properly handles the edge case when no primes exist in the range.

data/book-sets.json (1)

20-22: LGTM! Problem metadata updates align with PR objectives.

The addition of problem IDs (1071, 1431, 3583, 3602) and their categorization across different book sets (LeetCode 75, All, Visualization) is consistent with the PR's stated goal of adding solutions for new problems.

Also applies to: 60-66, 69-69

explanations/3583/en.md (1)

1-56: LGTM! Comprehensive and well-structured documentation.

The explanation clearly articulates the two-map frequency counting strategy, provides complexity analysis, and includes a detailed trace walkthrough. The documentation follows the project's structured format and effectively explains the O(n) optimization over the brute force O(n³) approach.

solutions/3583/01.py (1)

3-42: LGTM! Correct implementation of two-map frequency counting.

The solution correctly implements the O(n) algorithm using two frequency maps (freq_before and freq_after) to count special triplets. The logic properly:

  • Initializes freq_after with all elements
  • Moves elements from freq_after to freq_before as we iterate
  • Counts valid (i, k) pairs for each middle position j
  • Applies modulo arithmetic correctly
solutions/3760/01.py (2)

2-7: LGTM! Simple and correct implementation.

The solution correctly counts distinct characters to determine the maximum number of substrings with distinct starting characters. The implementation is clean and efficient at O(n) time and O(1) space (bounded by 26 characters).


2-2: No API change concern—different problems have different method signatures.

The method maxDistinct(self, s: str) is the correct signature for LeetCode problem 3760. The minimumCost method referenced in your concern belongs to problem 3759. Each problem has its own independent solution with appropriate method signatures, so this is not a breaking change.

solutions/3761/01.py (2)

3-5: Consider potential edge case in reverse_num.

The reverse_num function uses string reversal which will preserve leading zeros after reversal (e.g., 100"001"1). While int() handles this correctly, be aware that this behavior might not match certain problem requirements if leading zeros have special meaning.

Verify that the problem statement doesn't require special handling for numbers with trailing zeros (which become leading zeros after reversal).


7-21: LGTM! Efficient single-pass mirror pair detection.

The algorithm correctly identifies mirror pairs using a hash map to track reversed values. The logic properly:

  • Maintains a map from reversed values to their most recent indices
  • Checks if the current number matches any previously seen reversed value
  • Updates the minimum distance when a match is found
  • Returns -1 when no pairs exist
explanations/3760/en.md (1)

1-51: LGTM! Clear and concise documentation.

The explanation effectively articulates the key insight that the maximum number of substrings equals the number of distinct characters, since each substring must start with a unique character. The documentation includes helpful examples and complexity analysis.

explanations/3772/en.md (2)

9-10: LGTM! Clear explanation of time/space complexity.

The O(n) rerooting DP approach is correctly documented with appropriate space complexity for tree and DP arrays.


25-28: LGTM! Rerooting decomposition is accurate.

The decomposition correctly describes the two-phase approach: computing down[node] in the first DFS, then using the rerooting formula to derive ans[node] for all roots.

explanations/3771/en.md (3)

9-10: LGTM! Complexity analysis is accurate.

The O(n log n) time complexity from n binary searches and O(n) space for prefix sums is correctly stated.


24-28: LGTM! Algorithm decomposition is clear and correct.

The threshold derivation requirement[j] - hp + prefix[j+1] and the binary search approach to count valid starting positions are well explained.


42-46: LGTM! Trace walkthrough correctly demonstrates the algorithm.

The step-by-step table clearly shows threshold computation, binary search results, and cumulative score accumulation.

solutions/3772/01.py (2)

36-43: LGTM! Rerooting formula implementation is correct.

The parent contribution calculation ans[parent] - max(0, down[node]) correctly removes the child's contribution from the parent's answer before adding it to the child's subtree score.


17-29: Recursion limit is not a practical concern for LeetCode's environment.

Python's default recursion limit is ~1000, but LeetCode's Python runner uses ~550,000. With n up to 10^5, the worst-case tree depth (linear chain of 100,000 nodes) remains well below LeetCode's limit. While a deeply skewed tree could hit the local 1000-limit during development, this won't be an issue on LeetCode. Calling sys.setrecursionlimit() is unnecessary here and risks masking other performance issues.

books/Visualization.md (1)

145-149: LGTM! Solution implementation is correct and clean.

The solution correctly finds the maximum once, then uses a list comprehension to compare each kid's potential total against the maximum.

books/LeetCode_75.md (2)

520-581: AI-generated summary conflicts with actual changes.

The summary claims the 1431 entry "appears twice in the file as separate blocks," but the provided code shows only one addition block (lines 520–581). The duplicate headers within that block (at lines 520–521 and 525–527) are formatting elements consistent with other multi-section problems in the file (like 1207, 2215, 1657), not separate content blocks. Please verify whether the summary accurately reflects the scope of the PR or if a duplicate entry exists elsewhere.


576-580: Solution logic is correct and idiomatic.

The implementation correctly identifies kids whose candy count plus extras meets or exceeds the current maximum. The list comprehension is clean and efficient.

Comment on lines +8925 to +8930
## 1431. Kids With the Greatest Number of Candies [Easy]
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

### Explanation

## 1431. Kids With the Greatest Number of Candies [Easy]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Remove the duplicate 1431 header block (keep the fuller section that follows).

You have two consecutive "1431" headings; the first is a stub. Drop the first to avoid duplication and resolve MD024.

Apply this diff:

-## 1431. Kids With the Greatest Number of Candies [Easy]
-https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
-
-### Explanation
+<!-- removed duplicate stub header; kept the full section below -->
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
## 1431. Kids With the Greatest Number of Candies [Easy]
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
### Explanation
## 1431. Kids With the Greatest Number of Candies [Easy]
<!-- removed duplicate stub header; kept the full section below -->
## 1431. Kids With the Greatest Number of Candies [Easy]
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

8926-8926: Bare URL used

(MD034, no-bare-urls)


8930-8930: Multiple headings with the same content

(MD024, no-duplicate-heading)

🤖 Prompt for AI Agents
In books/All.md around lines 8925 to 8930, there are two consecutive "## 1431.
Kids With the Greatest Number of Candies [Easy]" header blocks; remove the first
stub header block (the shorter duplicate) and keep the fuller section that
follows so the duplicate heading is eliminated and MD024 is resolved.

Comment on lines +89 to +96
## 1431. Kids With the Greatest Number of Candies [Easy]
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

### Explanation

## 1431. Kids With the Greatest Number of Candies [Easy]

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Remove duplicate heading structure.

The problem section has a duplicated heading: ## 1431. Kids With the Greatest Number of Candies appears at both line 89 and line 94. This creates confusing document structure.

 ## 1431. Kids With the Greatest Number of Candies [Easy]
 https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

 ### Explanation

-## 1431. Kids With the Greatest Number of Candies [Easy]
-
-https://leetcode.com/problems/kids-with-the-greatest-number-of-candies
-
 ## Description
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
## 1431. Kids With the Greatest Number of Candies [Easy]
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
### Explanation
## 1431. Kids With the Greatest Number of Candies [Easy]
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies
## 1431. Kids With the Greatest Number of Candies [Easy]
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
### Explanation
🧰 Tools
🪛 LanguageTool

[style] ~89-~89: The word ‘Greatest’ tends to be overused in this context. Consider an alternative.
Context: ...next = next ``` ## 1431. Kids With the Greatest Number of Candies [Easy] https://leetcode.com/...

(A_GREAT_NUMBER)


[style] ~94-~94: The word ‘Greatest’ tends to be overused in this context. Consider an alternative.
Context: ...### Explanation ## 1431. Kids With the Greatest Number of Candies [Easy] https://leetcode.com...

(A_GREAT_NUMBER)

🪛 markdownlint-cli2 (0.18.1)

90-90: Bare URL used

(MD034, no-bare-urls)


94-94: Multiple headings with the same content

(MD024, no-duplicate-heading)


96-96: Bare URL used

(MD034, no-bare-urls)

🤖 Prompt for AI Agents
In books/Visualization.md around lines 89 to 96, there is a duplicated heading
and link block for "## 1431. Kids With the Greatest Number of Candies" appearing
twice; remove the redundant copy (either the first or second occurrence) so the
problem appears once, keeping a single heading and the canonical
link/description to restore proper document structure and avoid repeated
content.

Comment on lines +133 to +136
## Hint
For each kid, check if their candies plus `extraCandies` is at least as much as the current maximum.

## Explanation
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Remove duplicate ## Hint and ## Explanation headings.

These headings duplicate earlier structure in the same problem section. The Hint content at line 134 should use ### Hint to be consistent with other problems in this file, and the duplicate ## Explanation at line 136 should be removed entirely since the explanation content is already provided.

-## Hint
+### Hint
 For each kid, check if their candies plus `extraCandies` is at least as much as the current maximum.

-## Explanation
 First, you want to know the highest number of candies any kid currently has...
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

133-133: Multiple headings with the same content

(MD024, no-duplicate-heading)


136-136: Multiple headings with the same content

(MD024, no-duplicate-heading)

🤖 Prompt for AI Agents
In books/Visualization.md around lines 133 to 136, there are duplicate section
headings: change the "## Hint" at line 134 to "### Hint" to match other
problems, and remove the duplicate "## Explanation" heading at line 136 entirely
(keeping any explanation content that already exists elsewhere); ensure
surrounding headings and spacing remain consistent with the file's heading
hierarchy.

**1.2 High-level approach:**
We process each position j as the middle element. We maintain two frequency maps: one for elements before j (freq_before) and one for elements after j (freq_after). For each j, we count how many i < j have nums[i] == target and how many k > j have nums[k] == target, then multiply these counts.

![Frequency counting for triplets visualization](https://assets.leetcode.com/static_assets/others/frequency-counting-triplets.png)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# Check if the external image URL is accessible
curl -I -s -o /dev/null -w "%{http_code}" "https://assets.leetcode.com/static_assets/others/frequency-counting-triplets.png"

Repository: romankurnovskii/leetcode-apps

Length of output: 76


🏁 Script executed:

# Search for project guidelines on asset hosting in documentation
git ls-files | grep -E "(README|CONTRIBUTING|GUIDELINES|docs)" | head -20

Repository: romankurnovskii/leetcode-apps

Length of output: 98


🏁 Script executed:

# Look for patterns of image references in other markdown files
rg "!\[.*\]\(https?://" --type md | head -20

Repository: romankurnovskii/leetcode-apps

Length of output: 2286


🏁 Script executed:

# Check if there are any local image assets in the repository
fd -e png -e jpg -e jpeg -e gif -e svg | head -20

Repository: romankurnovskii/leetcode-apps

Length of output: 55


Fix broken image URL.

The image URL returns a 404 error. Other documentation assets in the repository use https://assets.leetcode.com/uploads/ path; verify the correct URL or replace with a working asset reference.

🤖 Prompt for AI Agents
In explanations/3583/en.md around line 16, the image link
https://assets.leetcode.com/static_assets/others/frequency-counting-triplets.png
returns 404; update the URL to the correct working asset (likely under
https://assets.leetcode.com/uploads/) or replace it with an existing asset path
in the repo, ensuring the filename and directory match the uploads path and
verifying the image loads before committing.

The key insight is that each substring must start with a distinct character. Since we can only use each starting character once, the maximum number of substrings equals the number of distinct characters in the string.

![DP with substring matching visualization](https://assets.leetcode.com/static_assets/others/dp-substring-matching.png)
![Distinct characters visualization](https://assets.leetcode.com/static_assets/others/distinct-characters.png)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if the external image URL is accessible
curl -I -s -o /dev/null -w "%{http_code}" "https://assets.leetcode.com/static_assets/others/distinct-characters.png"

Repository: romankurnovskii/leetcode-apps

Length of output: 76


🏁 Script executed:

# Search for project guidelines about external assets or documentation standards
find . -type f \( -name "README*" -o -name "CONTRIBUTING*" -o -name "GUIDELINES*" -o -name "*.md" \) | head -20 | xargs grep -l "asset\|image\|external\|documentation" 2>/dev/null | head -10

Repository: romankurnovskii/leetcode-apps

Length of output: 299


🏁 Script executed:

# Check the structure of the explanations directory to understand the asset handling pattern
ls -la explanations/ | head -20

Repository: romankurnovskii/leetcode-apps

Length of output: 1125


🏁 Script executed:

# Look for any other image references in markdown files to see the pattern
rg "!\[.*\]\(https?://" explanations/ | head -20

Repository: romankurnovskii/leetcode-apps

Length of output: 2216


🏁 Script executed:

# Check CONTRIBUTING.md for guidelines about assets
cat CONTRIBUTING.md | grep -A 5 -B 5 -i "asset\|image\|external"

Repository: romankurnovskii/leetcode-apps

Length of output: 629


🏁 Script executed:

# Check README.md for asset guidelines
cat README.md | grep -A 5 -B 5 -i "asset\|image\|external"

Repository: romankurnovskii/leetcode-apps

Length of output: 809


🏁 Script executed:

# Let's examine the file in question to understand context
cat -n explanations/3760/en.md | head -25

Repository: romankurnovskii/leetcode-apps

Length of output: 1855


🏁 Script executed:

# Test a few other LeetCode image URLs from the repo to see if they're accessible
echo "Testing other LeetCode CDN images..."
curl -I -s -o /dev/null -w "distinct-characters.png: %{http_code}\n" "https://assets.leetcode.com/static_assets/others/distinct-characters.png"
curl -I -s -o /dev/null -w "frequency-counting-triplets.png: %{http_code}\n" "https://assets.leetcode.com/static_assets/others/frequency-counting-triplets.png"
curl -I -s -o /dev/null -w "oranges.png: %{http_code}\n" "https://assets.leetcode.com/uploads/2019/02/16/oranges.png"
curl -I -s -o /dev/null -w "interleave.jpg: %{http_code}\n" "https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg"

Repository: romankurnovskii/leetcode-apps

Length of output: 212


Fix broken image URL.

The image at line 16 returns a 404 error. The LeetCode CDN path /static_assets/others/ appears to be defunct. Replace with a working alternative or update the URL to match accessible paths used elsewhere in the repository (e.g., /uploads/ paths).

🤖 Prompt for AI Agents
In explanations/3760/en.md around line 16, the image URL uses a defunct LeetCode
CDN path (/static_assets/others/) causing a 404; update the markdown image link
to point to a working asset (for example replace the URL with the repository's
accessible uploads path or another valid hosted image URL used elsewhere) so the
image loads correctly, ensuring the alt text and filename remain appropriate.

We use tree dynamic programming with rerooting. For each node as root, we perform DFS to find the maximum score of connected subgraphs containing that root.
We use tree dynamic programming with efficient rerooting. First, we compute subtree scores from an arbitrary root. Then, we use rerooting to compute answers for all nodes in O(n) time by efficiently transferring parent contributions to children.

![Tree DP visualization](https://assets.leetcode.com/static_assets/others/tree-dp-rerooting.png)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

curl -sI "https://assets.leetcode.com/static_assets/others/tree-dp-rerooting.png" | head -n 1

Repository: romankurnovskii/leetcode-apps

Length of output: 84


The image URL returns HTTP 404 (Not Found).

The LeetCode CDN URL https://assets.leetcode.com/static_assets/others/tree-dp-rerooting.png is inaccessible. Either provide a valid image URL or remove the broken image link.

🤖 Prompt for AI Agents
explanations/3772/en.md around line 16: the image URL used
(https://assets.leetcode.com/static_assets/others/tree-dp-rerooting.png) returns
HTTP 404; replace the broken CDN link with a valid image URL or remove the
markdown image tag altogether — preferably upload the correct image to project
assets or a reachable CDN, update the markdown to reference that new path, and
verify the link loads successfully before committing.

Comment on lines +1 to +2
class Solution:
def specialTriplets(self, nums: List[int]) -> int:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Add missing typing import.

The List type hint is used without importing it from the typing module, which will cause a runtime NameError.

Apply this diff to add the import:

+from typing import List
+
 class Solution:
     def specialTriplets(self, nums: List[int]) -> int:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
class Solution:
def specialTriplets(self, nums: List[int]) -> int:
from typing import List
class Solution:
def specialTriplets(self, nums: List[int]) -> int:
🧰 Tools
🪛 Ruff (0.14.8)

2-2: Undefined name List

(F821)

🤖 Prompt for AI Agents
In solutions/3583/01.py around lines 1 to 2, the type hint List is used but not
imported; add the missing import by inserting "from typing import List" at the
top of the file (before the Solution class) so the List name is defined and the
type hint no longer raises a NameError.

Comment on lines 1 to +2
class Solution:
def countPaths(self, n: int, edges: List[List[int]]) -> int:
# Sieve of Eratosthenes to find primes
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
def minMirrorPairDistance(self, nums: List[int]) -> int:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Add missing typing import.

The List type hint is used without importing it from the typing module, which will cause a runtime NameError.

Apply this diff to add the import:

+from typing import List
+
 class Solution:
     def minMirrorPairDistance(self, nums: List[int]) -> int:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
class Solution:
def countPaths(self, n: int, edges: List[List[int]]) -> int:
# Sieve of Eratosthenes to find primes
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
def minMirrorPairDistance(self, nums: List[int]) -> int:
from typing import List
class Solution:
def minMirrorPairDistance(self, nums: List[int]) -> int:
🧰 Tools
🪛 Ruff (0.14.8)

2-2: Undefined name List

(F821)

🤖 Prompt for AI Agents
In solutions/3761/01.py around lines 1 to 2, the type hint List is used but not
imported; add the missing import from typing by inserting "from typing import
List" at the top of the file (above the class definition) so the type annotation
resolves correctly.

if current_hp >= requirement[j]:
score += 1
res += score
import bisect
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Move the import to the top of the file.

The import bisect statement should be placed at the top of the file, following PEP 8 conventions. Placing imports within function bodies is non-idiomatic and can impact readability.

Apply this diff to move the import:

+from bisect import bisect_left
+
 class Solution:
     def totalScore(self, hp: int, damage: List[int], requirement: List[int]) -> int:
         n = len(damage)
@@ -14,8 +16,7 @@
         # => prefix[i] >= requirement[j] - hp + prefix[j+1]
         
         res = 0
-        import bisect
         for j in range(n):
             threshold = requirement[j] - hp + prefix[j + 1]
             # Use binary search to find first index where prefix[i] >= threshold
             # Since prefix is non-decreasing, we can use bisect_left
-            idx = bisect.bisect_left(prefix, threshold, hi=j + 1)
+            idx = bisect_left(prefix, threshold, hi=j + 1)
             # All indices from idx to j (inclusive) satisfy the condition
             res += max(0, j + 1 - idx)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import bisect
from bisect import bisect_left
class Solution:
def totalScore(self, hp: int, damage: List[int], requirement: List[int]) -> int:
n = len(damage)
# ... (earlier code to compute prefix array)
# => prefix[i] >= requirement[j] - hp + prefix[j+1]
res = 0
for j in range(n):
threshold = requirement[j] - hp + prefix[j + 1]
# Use binary search to find first index where prefix[i] >= threshold
# Since prefix is non-decreasing, we can use bisect_left
idx = bisect_left(prefix, threshold, hi=j + 1)
# All indices from idx to j (inclusive) satisfy the condition
res += max(0, j + 1 - idx)
🤖 Prompt for AI Agents
In solutions/3771/01.py around line 17, the import bisect is inside the
function; move the line "import bisect" to the module top with other imports
(just after any shebang/comments and before module-level constants or functions)
so imports follow PEP8 and improve readability.

Comment on lines +2 to +4
def maxSubgraphScore(
self, n: int, edges: List[List[int]], good: List[int]
) -> List[int]:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Add missing List import from typing.

Ruff correctly identifies that List is undefined. This will cause a NameError at runtime.

Add the import at the top of the file:

+from typing import List
+
 class Solution:
     def maxSubgraphScore(
         self, n: int, edges: List[List[int]], good: List[int]
     ) -> List[int]:

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.14.8)

3-3: Undefined name List

(F821)


3-3: Undefined name List

(F821)


3-3: Undefined name List

(F821)


4-4: Undefined name List

(F821)

🤖 Prompt for AI Agents
In solutions/3772/01.py around lines 2 to 4, the function signature uses List
from typing but List is not imported; add "from typing import List" (or include
List in an existing typing import) at the top of the file so the name List is
defined and the code no longer raises a NameError.

@romankurnovskii romankurnovskii merged commit 4dfee7b into main Dec 9, 2025
2 of 3 checks passed
@romankurnovskii romankurnovskii deleted the problems-3583-3772-3771-3770-3769-3768-3767-3766-3765-3764-3762-3761-3760 branch December 9, 2025 07:52
Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is being reviewed by Cursor Bugbot

Details

You are on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle.

To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.

res = []
for num in nums:
# Find closest palindrome
# Use binary search to find closest palindrome
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Insufficient palindrome range causes incorrect results near boundary

The palindrome generation only considers numbers from 1 to 5000, but for input values near 5000, the closest binary palindrome might be greater than 5000. For example, 5461 (binary: 1010101010101) is a palindrome with distance 461 from 5000, which is closer than 4097 (distance 903). Since the code doesn't generate palindromes beyond 5000, it returns incorrect results for values where a closer palindrome exists above the range.

Fix in Cursor Fix in Web

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants