Search⌘ K
AI Features

Reorganize String

Explore how to rearrange characters in a string to ensure no two adjacent letters are the same. Understand the constraints and apply problem-solving techniques involving heaps to generate a valid string arrangement or determine if reorganization is impossible.

Statement

Given a string, str, rearrange it so that any two adjacent characters are not the same. If such a reorganization of the characters is possible, output any possible valid arrangement. Otherwise, return an empty string.

Constraints:

  • 11\leq str.length 500\leq500
  • Input string consists of lowercase English letters.

Examples

canvasAnimation-image
1 / 3

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check that if you’re solving the correct problem:

Reorganize String

1.

(Select all that apply.) What is the output if str = "programming"Multi-select

A.

“programing”

B.

“rgmrgmpiano”

C.

“rmpimrggano”

D.

“programimng”


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground:

Java
usercode > Main.java
import java.util.*;
public class Main{
public static String reorganizeString(String string1) {
// Replace this placeholder return statement with your code
return "";
}
}
Reorganize String