-
Notifications
You must be signed in to change notification settings - Fork 1
Add solutions and explanations for problems 3583, 3772, 3771, 3770, 3766, 3768, 3767, 3765, 3761, 3760 #112
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
…766, 3768, 3767, 3765, 3761, 3760
|
🧙 Sourcery is reviewing your pull request! Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
Caution Review failedThe pull request is closed. WalkthroughAdded 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
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. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this 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: Movebisectimport out of the per‑element loop; verify bounds vs. constraintsThe binary‑search logic for picking the nearest palindrome via
bisect_leftlooks correct, and the two neighbor checks (atidxandidx - 1) are sufficient.Two small follow‑ups:
import bisectinsidefor 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)
- 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., whethernums[i]can be0or exceed5000) and maybe add a short comment explaining why5000is 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** +### ConstraintsAlso applies to: 8960-8960
solutions/3770/01.py (1)
18-28: Remove redundant condition on Line 27.The condition
current_sum <= non Line 27 is redundant because the loop breaks on Line 25 whencurrent_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 defaultdictimport 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
📒 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. TheminimumCostmethod 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_numfunction uses string reversal which will preserve leading zeros after reversal (e.g.,100→"001"→1). Whileint()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 deriveans[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.
| ## 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] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| ## 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.
| ## 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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| ## 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.
| ## Hint | ||
| For each kid, check if their candies plus `extraCandies` is at least as much as the current maximum. | ||
|
|
||
| ## Explanation |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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. | ||
|
|
||
|  |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 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 -20Repository: romankurnovskii/leetcode-apps
Length of output: 98
🏁 Script executed:
# Look for patterns of image references in other markdown files
rg "!\[.*\]\(https?://" --type md | head -20Repository: 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 -20Repository: 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. | ||
|
|
||
|  | ||
|  |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 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 -10Repository: 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 -20Repository: 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 -20Repository: 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 -25Repository: 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. | ||
|
|
||
|  |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
curl -sI "https://assets.leetcode.com/static_assets/others/tree-dp-rerooting.png" | head -n 1Repository: 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.
| class Solution: | ||
| def specialTriplets(self, nums: List[int]) -> int: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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.
| 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: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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 |
There was a problem hiding this comment.
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.
| 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.
| def maxSubgraphScore( | ||
| self, n: int, edges: List[List[int]], good: List[int] | ||
| ) -> List[int]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
…3766-3765-3764-3762-3761-3760
There was a problem hiding this 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 |
There was a problem hiding this comment.
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.
Summary
This PR adds solutions and explanations for 10 LeetCode problems that have been verified as accepted.
Problems Added
Notes
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:
Bug Fixes:
Enhancements:
Summary by CodeRabbit
New Features
Documentation
Chores
✏️ 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/3583/01.py(freq maps, O(n)).solutions/3760/01.pywith distinct-char count approach.solutions/3761/01.pywith mirror-pair distance via hash map.solutions/3766/01.pyusing binary search over precomputed palindromes.solutions/3770/01.pyto consecutive prime sums from 2 only.solutions/3771/01.pyto prefix sums + binary search (O(n log n)).solutions/3772/01.pyto rerooting DP (O(n)).solutions/3762/01.py,solutions/3769/01.py.explanations/3583/en.md,explanations/3760/en.md,explanations/3761/en.md,explanations/3771/en.md,explanations/3772/en.mdwith updated strategies.explanations/3762/en.md,explanations/3769/en.md.books/All.md,books/LeetCode_75.md,books/Visualization.md.data/book-sets.jsonproblem listings.Written by Cursor Bugbot for commit cb2768e. This will update automatically on new commits. Configure here.