bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 358. Rearrange String k Distance Apart

358. Rearrange String k Distance Apart

Leetcode Solutions

Priority Queue Approach

  1. Create a frequency map freq from character to integer.
  2. Create a max heap free to store characters by their frequency, with the highest frequency at the top.
  3. Initialize an empty queue busy to keep track of 'busy' characters.
  4. While the length of the answer string ans is less than the length of s: a. If the size of busy is k, pop from busy and add the character back to free. b. If free is empty, return an empty string. c. Pop the top character from free, append it to ans, decrement its frequency, and if the frequency is not zero, add it to busy.
  5. Return ans.
UML Thumbnail

Greedy Approach with Segmentation

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...