Skip to content

Conversation

@Once-1296
Copy link
Contributor

@Once-1296 Once-1296 commented Oct 19, 2025

PR Title Format: 3720. Lexicographically Smallest Permutation Greater Than Target
(https://leetcode.com/problems/lexicographically-smallest-permutation-greater-than-target/)

Intuition

Size of string is in [1,300]. Approach must be O(n^2) or O(n^2 logn).
When can a string be greater than another string of the same length?
if and only if for all characters at j in [0,i] s[j] = t[j]
and s[i+1]>t[i+1]
where i +1 < n (for proper indexing)

Approach

  1. Create a frequency map of string s, initialise ans as empty string
  2. Run a loop from i=0 to i =n-1
    a. Try to match the first ith characters of s and target (0 to i-1 in 0 indexing)
    b. for the ith (0 indexed) character of target, find the first character greater than it in the remaining frequency map
    c. if no such character found continue
    d. else for all indices from i +1 onwards till n-1, put all remaining chars of map in ascending order.
    e. if ans is empty string, set ans as found string, else set ans as minimum between ans and found string
  3. return ans

Code Solution (C++)

    // Your code goes here
    class Solution {
public:
    string lexGreaterPermutation(string s, string target) {
        string ans ="";
        int n = s.length();
        map<char,int>mp;
        for(auto&e:s)mp[e]++;
        for(int i =0;i<n;i++)
            {
                map<char,int> m2=mp;
                string res ="";
                bool ip=1;
                for(int j = 0;j<i;j++)
                    {
                        char e=target[j];
                        if(!m2.count(e))
                        {
                            ip=0;
                            break;
                        }
                        res+=e;
                        m2[e]--;
                        if(m2[e]==0)m2.erase(e);
                    }
                if(ip)
                {
                            char e = target[i];
                            auto it = m2.upper_bound(e);
                            if(it!=m2.end())
                            {
                                res+=it->first;
                                it->second--;
                                if(it->second==0)m2.erase(it);
                            }
                    else continue;
                    for(auto&e:m2)
                        {
                            while(e.second--)res+=e.first;
                        }
                    if(ans =="")ans=res;
                    else ans = min(ans,res);
                }
            }
        return ans;
    }
};

Related Issues

Closes Issue: #181

By submitting this PR, I confirm that:

  • [✔️ ] This is my original work not totally AI generated
  • [ ✔️] I have tested the solution thoroughly on leetcode
  • [ ✔️] I have maintained proper PR description format
  • [ ✔️] This is a meaningful contribution, not spam

Summary by Sourcery

New Features:

  • Add C++ implementation for the LeetCode 3720 problem to compute the lexicographically smallest permutation greater than a given target string

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 19, 2025

Reviewer's Guide

This PR adds a new C++ solution for LeetCode 3720 that computes the lexicographically smallest permutation of one string greater than a target by scanning pivot positions, matching prefixes, and constructing suffixes via frequency maps and map.upper_bound.

Class diagram for Solution and lexGreaterPermutation method

classDiagram
class Solution {
  +string lexGreaterPermutation(string s, string target)
}
Loading

Flow diagram for lexGreaterPermutation algorithm

flowchart TD
    A["Start"] --> B["Initialize ans as empty string"]
    B --> C["Build frequency map mp from s"]
    C --> D["For i in 0 to n-1"]
    D --> E["Copy mp to m2"]
    E --> F["Build prefix: for j in 0 to i-1, match target[j] in m2"]
    F --> G{Prefix matched?}
    G -- No --> D
    G -- Yes --> H["Find first char > target[i] in m2"]
    H --> I{Found?}
    I -- No --> D
    I -- Yes --> J["Add char to result, update m2"]
    J --> K["Append remaining chars in m2 in ascending order"]
    K --> L["Update ans if result is smaller"]
    L --> D
    D --> M["Return ans"]
Loading

File-Level Changes

Change Details Files
New C++ solution implementing lexGreaterPermutation algorithm
  • Initialize frequency map of input string
  • Iterate pivot index i to match target prefix by consuming map counts
  • At pivot, select next greater char using map.upper_bound
  • Append remaining chars in sorted order to form candidate
  • Track and update the minimal valid permutation as answer
3720. Lexicographically Smallest Permutation Greater Than Target.cpp

Possibly linked issues

  • #3720: The PR provides the solution for issue 3720, with identical problem description, approach, intuition, and C++ code.

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

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Thanks for raising the PR, the owner will be review it soon' keep patience, keep contributing>>>!!! make sure you have star ⭐ the repo

Copy link

@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.

Hey there - I've reviewed your changes - here's some feedback:

  • Since the first valid break position produces the lexicographically smallest answer, you can return immediately when you construct it instead of tracking and comparing all candidates.
  • Consider replacing the std::map<char,int> with a fixed‐size array (e.g., vector of size 26) to avoid repeated map copying and speed up lookups.
  • Rename variables like mp, m2, ip, and res to more descriptive names to improve code readability and maintainability.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Since the first valid break position produces the lexicographically smallest answer, you can return immediately when you construct it instead of tracking and comparing all candidates.
- Consider replacing the std::map<char,int> with a fixed‐size array (e.g., vector<int> of size 26) to avoid repeated map copying and speed up lookups.
- Rename variables like mp, m2, ip, and res to more descriptive names to improve code readability and maintainability.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@Once-1296 Once-1296 changed the title Added LC 3720 3720. Lexicographically Smallest Permutation Greater Than Target] Oct 19, 2025
@Once-1296 Once-1296 changed the title 3720. Lexicographically Smallest Permutation Greater Than Target] 3720. Lexicographically Smallest Permutation Greater Than Target Oct 19, 2025
@SjxSubham
Copy link
Owner

@Once-1296

All looks good to me..

Star the repo ⭐ as well..

@SjxSubham SjxSubham linked an issue Oct 19, 2025 that may be closed by this pull request
4 tasks
@Once-1296
Copy link
Contributor Author

@SjxSubham I have starred the repo, Please merge my PR now.

@SjxSubham SjxSubham merged commit 4a1fd39 into SjxSubham:main Oct 20, 2025
2 checks passed
@github-actions
Copy link

🎉 Congrats on getting your PR merged in, @Once-1296! 🙌🏼

Thanks for your contribution every effort helps improve the project.

Looking forward to seeing more from you! 🥳✨

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.

3720: Lexicographically Smallest Permutation Greater Than Target

2 participants