Skip to content

Conversation

@vikahaze
Copy link
Collaborator

@vikahaze vikahaze commented Dec 10, 2025

Summary

This PR adds solutions and explanations for 3 LeetCode problems that passed all test cases:

Problem 3722: Lexicographically Smallest String After Reverse

  • Difficulty: Medium
  • Status: ✅ Accepted (999/999 test cases)
  • Approach: Try all possible prefix and suffix reversals, keep the lexicographically smallest result
  • Time Complexity: O(n²)
  • Space Complexity: O(n)

Problem 3727: Maximum Alternating Sum of Squares

  • Difficulty: Medium
  • Status: ✅ Accepted (691/691 test cases)
  • Approach: Sort squares in descending order, assign largest to positive positions (even indices) and smallest to negative positions (odd indices)
  • Time Complexity: O(n log n)
  • Space Complexity: O(n)

Problem 3759: Count Elements With at Least K Greater Values

  • Difficulty: Medium
  • Status: ✅ Accepted (927/927 test cases)
  • Approach: Sort array, use binary search to count elements strictly greater than each distinct value
  • Time Complexity: O(n log n)
  • Space Complexity: O(n)

Files Added

  • solutions/3722/01.py
  • explanations/3722/en.md
  • solutions/3727/01.py
  • explanations/3727/en.md
  • solutions/3759/01.py
  • explanations/3759/en.md

All solutions follow the repository's coding standards and include detailed explanations following the template structure.

Summary by Sourcery

Add and refine solutions and explanations for LeetCode problems 3722, 3727, and 3759 while cleaning up outdated/duplicated documentation entries.

New Features:

  • Provide an implementation for counting elements with at least k greater values (problem 3759) using sorting and binary search.
  • Implement a rearrangement-based solution for maximizing the alternating sum of squares (problem 3727).
  • Implement a string reversal-based solution for producing the lexicographically smallest string after one operation (problem 3722).

Bug Fixes:

  • Replace an unrelated string-conversion solution previously living under problem 3759 with the correct count-elements implementation.

Enhancements:

  • Clarify and restructure the English explanations for problems 3722, 3727, and 3759 with consistent sections on constraints, strategy, and step-by-step walkthroughs.

Documentation:

  • Remove duplicated documentation for problem 1431 'Kids With the Greatest Number of Candies' from multiple book collections to reduce redundancy and noise.

Summary by CodeRabbit

  • Documentation

    • Removed problem 1431 from documentation resources
    • Updated explanations for problems 3722, 3727, and 3759 with improved clarity and restructured content
  • New Features

    • Added problem 3583 to the problems list
  • Refactor

    • Refactored code for problems 3722, 3727, and 3759 with improved implementation approaches and variable naming

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

…raphically Smallest String After Reverse, Maximum Alternating Sum of Squares, Count Elements With at Least K Greater Values
@coderabbitai
Copy link

coderabbitai bot commented Dec 10, 2025

Walkthrough

This PR removes documentation for problem 1431 from multiple markdown files, adds problem 3583 to the problem set, and rewrites/refactors explanations and solutions for problems 3722, 3727, and 3759. Problem 3759's solution undergoes a complete algorithmic change from Floyd-Warshall graph computation to binary-search-based counting.

Changes

Cohort / File(s) Summary
Problem 1431 documentation removal
books/All.md, books/LeetCode_75.md, books/Visualization.md
Removed entire content blocks for LeetCode 1431 - Kids With the Greatest Number of Candies [Easy], including descriptions, explanations, examples, constraints, hints, and solutions.
Problem set update
data/book-sets.json
Added problem 3583 to the AllProblems array, positioned before the 3602+ sequence.
Explanation rewrites
explanations/3722/en.md
Restructured Strategy section with clearer constraint/complexity framing, reworded high-level approach, and expanded step-by-step walkthrough with added table; no algorithmic changes.
Explanation restructuring
explanations/3727/en.md
Reformatted subsection headings, expanded constraints & complexity with explicit input size and edge cases, clarified high-level approach, rewrote brute force vs. optimized comparison, and expanded walkthrough table with corrected final value (12).
Complete explanation replacement
explanations/3759/en.md
Rewritten from graph-based string conversion problem (Floyd-Warshall) to numeric counting problem; shifted approach from shortest paths to sorting-based counting with binary search; replaced example narrative and trace sections accordingly.
Solution variable refactoring
solutions/3722/01.py
Renamed variables (reversed_strreversed_prefix/reversed_suffix, introduced candidate variable); no functional logic changes.
Solution refactoring
solutions/3727/01.py
Added type import for List, replaced iterative accumulation with direct calculation using sorted squares and prefix/suffix sums assigned to alternating positions; internal approach restructured but output preserved.
Solution algorithm replacement
solutions/3759/01.py
Complete method replacement: signature changed from minimumCost(source, target, original, changed, cost) to countElements(nums, k); algorithm shifted from graph initialization + Floyd-Warshall to sorting-based counting with binary search upper-bound checks.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • solutions/3759/01.py: Complete algorithmic rewrite from Floyd-Warshall graph computation to binary-search-based counting—verify correctness against intended problem definition and test edge cases.
  • explanations/3759/en.md: Problem framing completely changed from graph-based to numeric counting—verify content accuracy and alignment with the new solution.
  • explanations/3727/en.md: Multiple rewrites and new trace table with corrected values—validate walkthrough logic and final result (12).
  • data/book-sets.json: Verify problem 3583 is correctly positioned and doesn't conflict with existing entries.

Possibly related PRs

Suggested reviewers

  • romankurnovskii

Poem

🐰 Out with old candies, problem one-four-three-one,
In comes new 3583, sorting's begun!
Graphs fade to counting, Floyd-Warshall to binary search,
Explanations refined, each detail's a lurch—
Hop-skipping through changes, the problem set's blessed!

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 changeset: adding solutions and explanations for three LeetCode problems (3722, 3727, 3759).
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch problems-3577-3769-3759-3753-3747-3733-3732-3728-3727-3724-3723-3722

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.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Dec 10, 2025

Reviewer's Guide

Implements accepted solutions and refreshed explanations for LeetCode problems 3722, 3727, and 3759, refactors the corresponding Python implementations for clarity/efficiency, and removes duplicated content for problem 1431 from book indices.

Class diagram for new LeetCode Solution implementations

classDiagram
class Solution3722 {
  +str lexSmallest(str s)
}

class Solution3727 {
  +int maxAlternatingSum(List_int nums)
}

class Solution3759 {
  +int countElements(List_int nums, int k)
}

%% Represent logical grouping only; actual code uses separate Solution classes per file
Solution3722 ..> Solution3727 : independent_solutions
Solution3727 ..> Solution3759 : independent_solutions
Loading

File-Level Changes

Change Details Files
Refine implementation of lexicographically smallest string after one prefix/suffix reverse and align explanation structure.
  • Keep original algorithm of trying all prefix and all suffix reversals but rename intermediates for clarity (prefix/suffix vs generic reversed_str).
  • Clarify the written explanation: standardize section headings, spell out constraints and complexity bullets, and add step‑by‑step tables walking through prefix and suffix reversal examples.
  • Emphasize that brute-force over all 2n operations is optimal under current constraints and document edge cases where no smaller string exists.
solutions/3722/01.py
explanations/3722/en.md
Optimize and better document the maximum alternating sum of squares solution.
  • Replace absolute-value sorting with direct squaring of each element and sorting squares in descending order to simplify reasoning.
  • Compute number of positive (even index) and negative (odd index) positions analytically and use a sum-of-prefix minus suffix pattern instead of looping with index parity checks.
  • Update explanation to match the new implementation, clarifying the greedy reasoning, constraints, and a worked example consistent with the square-based approach.
solutions/3727/01.py
explanations/3727/en.md
Implement array-based counting of elements with at least k strictly greater values and synchronize explanation with the new algorithm.
  • Replace an unrelated Floyd–Warshall string-conversion implementation with a sort+binary-search based counting method over distinct values.
  • Use a single sorted copy of nums, compress equal values by running counts, and for each distinct value binary search the first greater element to determine whether it qualifies.
  • Document constraints, complexity, and a small traced example in the explanation file using the new sorted+binary-search approach.
solutions/3759/01.py
explanations/3759/en.md
Remove duplicated writeups for problem 1431 from book indices to keep the catalog DRY.
  • Delete the repeated 1431 "Kids With the Greatest Number of Candies" problem section from the main book index.
  • Remove the same duplicated 1431 entry from the LeetCode 75 and Visualization book indices to avoid redundancy and potential drift from the primary source.
books/All.md
books/LeetCode_75.md
books/Visualization.md

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

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: 0

🧹 Nitpick comments (1)
solutions/3727/01.py (1)

14-19: Remove unused variable num_negative.

The variable num_negative is calculated but never used. The slicing squares[num_positive:] on line 19 implicitly handles the negative positions.

Apply this diff:

-        # Count how many positive and negative positions we have
         num_positive = (n + 1) // 2  # Even indices: 0, 2, 4, ...
-        num_negative = n // 2  # Odd indices: 1, 3, 5, ...
         
         # Assign largest squares to positive positions, smallest to negative
         res = sum(squares[:num_positive]) - sum(squares[num_positive:])

Based on static analysis hints.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4dfee7b and 8d732ac.

📒 Files selected for processing (10)
  • books/All.md (0 hunks)
  • books/LeetCode_75.md (0 hunks)
  • books/Visualization.md (0 hunks)
  • data/book-sets.json (1 hunks)
  • explanations/3722/en.md (1 hunks)
  • explanations/3727/en.md (1 hunks)
  • explanations/3759/en.md (1 hunks)
  • solutions/3722/01.py (1 hunks)
  • solutions/3727/01.py (1 hunks)
  • solutions/3759/01.py (1 hunks)
💤 Files with no reviewable changes (3)
  • books/Visualization.md
  • books/All.md
  • books/LeetCode_75.md
🧰 Additional context used
🪛 LanguageTool
explanations/3722/en.md

[style] ~20-~20: Consider an alternative for the overused word “exactly”.
Context: ...y with the current best result. This is exactly what we do, and it's efficient enough g...

(EXACTLY_PRECISELY)

🪛 markdownlint-cli2 (0.18.1)
explanations/3727/en.md

5-5: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


7-7: Unordered list indentation
Expected: 0; Actual: 2

(MD007, ul-indent)


8-8: Unordered list indentation
Expected: 0; Actual: 2

(MD007, ul-indent)


9-9: Unordered list indentation
Expected: 0; Actual: 2

(MD007, ul-indent)


10-10: Unordered list indentation
Expected: 0; Actual: 2

(MD007, ul-indent)


12-12: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


18-18: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


20-20: Unordered list indentation
Expected: 0; Actual: 2

(MD007, ul-indent)


21-21: Unordered list indentation
Expected: 0; Actual: 2

(MD007, ul-indent)


23-23: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


33-33: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


39-39: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


43-43: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


61-61: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

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

16-16: Local variable num_negative is assigned to but never used

Remove assignment to unused variable num_negative

(F841)

🔇 Additional comments (7)
data/book-sets.json (1)

64-66: LGTM! Problem 3583 correctly added to the problem set.

The addition of problem 3583 to the "All" problems list is correctly positioned in sorted order before 3602.

solutions/3722/01.py (1)

1-22: LGTM! Clear variable naming improves readability.

The refactoring enhances code clarity without changing functionality:

  • reversed_prefix and reversed_suffix are more descriptive than the generic reversed_str
  • The candidate variable makes the comparison logic easier to follow
  • Algorithm correctly implements the brute force approach with O(n²) time complexity
explanations/3722/en.md (1)

1-67: LGTM! Comprehensive and accurate documentation.

The explanation clearly describes the algorithm with:

  • Correct complexity analysis (O(n²) time, O(n) space)
  • Detailed trace walkthrough showing prefix and suffix reversals
  • Accurate example demonstrating the solution ("dcab" → "acdb")
solutions/3727/01.py (1)

1-21: LGTM! Correct greedy algorithm implementation.

The solution correctly implements the optimal strategy:

  • Squares all numbers and sorts in descending order
  • Assigns largest squares to positive positions (even indices)
  • Computes the alternating sum efficiently using prefix/suffix sums
  • Time complexity O(n log n) as stated in PR objectives
solutions/3759/01.py (1)

1-38: LGTM! Correct implementation of counting algorithm.

The solution correctly implements the counting approach:

  • Sorts the array for efficient binary search
  • Iterates through distinct values with occurrence counting
  • Uses binary search to find the upper bound (first element strictly greater)
  • Correctly counts elements with at least k greater values
  • Time complexity O(n log n) as stated in PR objectives

The binary search implementation is correct for finding the first index with a value strictly greater than the current value.

explanations/3727/en.md (1)

1-61: LGTM! Clear and accurate documentation.

The explanation correctly describes the algorithm:

  • Accurate complexity analysis (O(n log n) time, O(n) space)
  • Clear high-level approach with greedy optimization strategy
  • Detailed trace walkthrough with correct result (12)
  • Example properly demonstrates sorting and position assignment
explanations/3759/en.md (1)

1-58: LGTM! Comprehensive and accurate documentation.

The explanation correctly describes the counting algorithm:

  • Accurate complexity analysis (O(n log n) time, O(n) space)
  • Clear explanation of the sorting and binary search approach
  • Detailed trace walkthrough with correct result (2)
  • Proper handling of distinct values and upper bound search

@romankurnovskii romankurnovskii merged commit 807cc5b into main Dec 10, 2025
2 checks passed
@romankurnovskii romankurnovskii deleted the problems-3577-3769-3759-3753-3747-3733-3732-3728-3727-3724-3723-3722 branch December 10, 2025 10:20
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