LeetCode 2182: Construct String With Repeat Limit Solution
Master LeetCode problem 2182 (Construct String With Repeat Limit), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2182. Construct String With Repeat Limit
Problem Explanation
Explanation
To solve this problem, we can iterate through the characters in the input string s and construct the output string repeatLimitedString by keeping track of the count of each character. We will append characters to the output string such that no character appears more than repeatLimit times in a row. To maximize the lexicographical order, we should prioritize appending characters that occur later in the alphabet.
We can achieve this by using a priority queue to store characters based on their frequency. We will repeatedly pop characters from the priority queue, append them to the output string, and update their counts until we reach the desired limit.
The time complexity of this solution is O(n log n) where n is the length of the input string s. The space complexity is O(n) due to the priority queue and the output string.
Solution Code
import java.util.*;
class Solution {
public String constructStringWithRepeatLimit(String s, int repeatLimit) {
StringBuilder repeatLimitedString = new StringBuilder();
Map<Character, Integer> countMap = new HashMap<>();
PriorityQueue<Character> pq = new PriorityQueue<>((a, b) -> countMap.get(b) - countMap.get(a) != 0 ? countMap.get(b) - countMap.get(a) : a - b);
for (char c : s.toCharArray()) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
pq.addAll(countMap.keySet());
while (!pq.isEmpty()) {
char curr = pq.poll();
int count = Math.min(repeatLimit, countMap.get(curr));
for (int i = 0; i < count; i++) {
repeatLimitedString.append(curr);
countMap.put(curr, countMap.get(curr) - 1);
}
if (countMap.get(curr) > 0) {
pq.add(curr);
}
}
return repeatLimitedString.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2182 (Construct String With Repeat Limit)?
This page provides optimized solutions for LeetCode problem 2182 (Construct String With Repeat Limit) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2182 (Construct String With Repeat Limit)?
The time complexity for LeetCode 2182 (Construct String With Repeat Limit) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2182 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2182 in Java, C++, or Python.