Rearrange a string so no neighbours match
I was asked this
No reports yet. Sign in to say where you were asked it.
Given a string s of lowercase English letters, rearrange its characters so that no two adjacent characters are equal. Every character of s must be used exactly once.
Implement:
-
reorganize(s) -> str: return any valid arrangement, or""if none exists. -
reorganize_smallest(s) -> str: return the lexicographically smallest valid arrangement, or""if none exists. The result is unique, so it can be graded exactly.
Constraints
0 <= len(s) <= 10^5-
scontains onlya-z.
Example 1
s = "ccbbaa"
reorganize(s) -> any valid answer, e.g. "cbacba"
reorganize_smallest(s) -> "abacbc"
Example 2
s = "aabbbb"
reorganize(s) -> "" (four b's cannot be separated by two a's)
Interviewers often start with part 1 and then ask for the deterministic answer, or ask that equal letters be at least k positions apart.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
