Leetcode Problem 2182. Construct String With Repeat Limit

2182. Construct String With Repeat Limit

Leetcode Solutions

Greedy Approach with Priority Queue and HashMap

  1. Count the frequency of each character in the input string s and store it in a hash map.
  2. Add all the characters and their frequencies to a priority queue, sorted in descending order of characters.
  3. Initialize an empty result string.
  4. While the priority queue is not empty: a. Extract the character with the highest frequency from the priority queue. b. Append the character to the result string up to repeatLimit times, reducing its frequency accordingly. c. If the frequency of the character is not exhausted, check if there is a next largest character in the priority queue. d. If there is, append that character once to the result string and re-insert it into the priority queue if it still has a remaining frequency. e. Re-insert the original character into the priority queue if it still has a remaining frequency.
  5. Return the result string.
UML Thumbnail

Counting Sort and Greedy Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...