LeetCode 0358. Rearrange String k Distance Apart Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0358. Rearrange String k Distance Apart

Description

Given a string s and an integer k, rearrange s such that the same characters are at least distance k from each other. If it is not possible to rearrange the string, return an empty string "".

 

Example 1:

Input: s = "aabbcc", k = 3
Output: "abcabc"
Explanation: The same letters are at least a distance of 3 from each other.

Example 2:

Input: s = "aaabc", k = 3
Output: ""
Explanation: It is not possible to rearrange the string.

Example 3:

Input: s = "aaadbbcc", k = 2
Output: "abacabcd"
Explanation: The same letters are at least a distance of 2 from each other.

 

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consists of only lowercase English letters.
  • 0 <= k <= s.length

Solutions

Solution 1: Greedy + Hash Table + Priority Queue (Max Heap)

We use a hash table or array cnt to count the occurrences of each character in the string. Then, we use a max heap pq to store each character and its count. Each element in the heap is a tuple (v, c), where v is the count and c is the character.

When rearranging the string, we repeatedly pop the top element (v, c) from the heap, add character c to the result string, and push (v-1, c) into a queue q. When the length of the queue q reaches k or more, we pop the front element; if its v is greater than 0, we push it back into the heap. Repeat this process until the heap is empty.

Finally, we check whether the length of the result string equals the original string. If so, we return the result string; otherwise, we return an empty string.

The time complexity is O(n log n), where n is the length of the string. The space complexity is O(|Σ|), where |Σ| is the size of the character set, which is 26 in this problem.

Related problems:

PythonJavaC++GoTypeScript
class Solution: def rearrangeString(self, s: str, k: int) -> str: cnt = Counter(s) pq = [(-v, c) for c, v in cnt.items()] heapify(pq) q = deque() ans = [] while pq: v, c = heappop(pq) ans.append(c) q.append((v + 1, c)) if len(q) >= k: e = q.popleft() if e[0]: heappush(pq, e) return "" if len(ans) < len(s) else "".join(ans)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !