00:00

Problem Statement

Input/Output Examples

Visual Explanation

Using the most frequent letter as early as possible keeps it from piling up at the end. If the only letter left equals the previous one, no valid arrangement exists.

Approaches

Both approaches place the most frequent letter carefully. The heap decides step by step; the even-slot method places letters by position.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. For these inputs both programs print the same arrangements, but in general they can return different valid answers, so each program also prints valid=true after checking its own result.

Complexity Analysis

Here n is the length of the string and k the number of distinct letters. The heap does n operations of cost log k; the even-slot method writes each character once.

Interview Tips and Recommended Approach

  • Check feasibility first. A letter with count above (n + 1) / 2 makes the task impossible.
  • Say that several answers are valid. Test by checking the neighbours and the letter counts, not by comparing with a fixed string.
  • Push letters back after placing. Forgetting to re-insert the skipped top letter loses characters.
  • Know the generalisation: keeping equal letters at least k apart uses the same heap plus a waiting queue.

Recommended Approach: Max-Heap Greedy

Why: it is a clear greedy rule backed by a standard data structure, and it extends naturally to the harder "at least k apart" version.