LeetCode 358, Hard. Topics: Greedy, Hash Table, String, Counting, Sorting, Heap (Priority Queue). View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:
Problem
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 "".
Examples
Constraints
1 <= s.length <= 3 * 10^5
s consists of only lowercase English letters.
0 <= k <= s.length
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026