HardHash TableStringGreedySortingHeap (Priority Queue)Counting

Rearrange String k Distance Apart

1 approach, code in every language

Problem description

You are given a string s and an integer k. Reorder the characters of s so that any two identical characters are separated by a distance of at least k positions.

If no such arrangement is possible, return an empty string. When k is 0 or 1 there is no spacing requirement, so the original string is already valid.

Example 1

Input: s = "aabbcc", k = 3

Output: "abcabc"

Each pair of identical letters ends up three positions apart, satisfying the distance requirement.

Example 2

Input: s = "aaabc", k = 3

Output: ""

There are three a's but only five slots, so at least two a's must land closer than three apart. It is impossible, so the answer is the empty string.

Constraints

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

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free