HardHash TableStringGreedySortingHeap (Priority Queue)Counting

Rearrange String k Distance Apart

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now