← All problems

3403. Find the Lexicographically Largest String from the Box I

MediumOpen on LeetCodeProblem statement

Problem Statement

3403. Find the Lexicographically Largest String From the Box I

Medium


You are given a string word, and an integer numFriends.

Alice is organizing a game for her numFriends friends. There are multiple rounds in the game, where in each round:

Find the lexicographically largest string from the box after all the rounds are finished.

 

Example 1:

Input: word = "dbca", numFriends = 2

Output: "dbc"

Explanation: 

All possible splits are:

Example 2:

Input: word = "gggg", numFriends = 4

Output: "g"

Explanation: 

The only possible split is: "g", "g", "g", and "g".

 

Constraints:

Java

Source file
class Solution {
    public String answerString(String word, int numFriends) {
        if (numFriends == 1)
            return word;
        int n = word.length(), maxLen = n - numFriends + 1;
        char startChar = word.charAt(0);
        Set<Integer> startIdx = new HashSet<>();
        for (int i = 0; i < n; i++) {
            char c = word.charAt(i);
            if (c > startChar) {
                startIdx.clear();
                startChar = c;
                startIdx.add(i);
            } else if (c == startChar)
                startIdx.add(i);
        }
        String ans = "";
        for (int i : startIdx) {
            String w = word.substring(i, Math.min(i + maxLen, n));
            System.out.println(w);
            if (ans.compareTo(w) < 1)
                ans = w;
        }
        return ans;
    }
}