Formatting a string to separate identical characters in JavaScript

In JavaScript, we often need to rearrange string characters so that no two identical characters are adjacent to each other. This is a classic string manipulation problem that requires careful character distribution.

The function should reorganize the characters in the input string such that no two identical characters are placed next to each other. If such an arrangement is possible, it returns the rearranged string; otherwise, it returns an empty string.

Problem Understanding

Given a string like 'add', we need to rearrange it to 'dad' where no two identical characters are adjacent. The key insight is that if any character appears more than half the total length (rounded up), it's impossible to separate all instances.

Example Input and Output

Input: 'add'
Output: 'dad'

Algorithm Approach

The solution uses a greedy approach:

  1. Count frequency of each character
  2. Check if rearrangement is possible
  3. Place characters alternately starting with the most frequent

Implementation

const str = 'add';

const formatString = (str = '') => {
    const map = {};
    
    // Count character frequencies
    for(let i = 0; i  {
        if(map[a]  maxAllowed){
        return "";
    }
    
    // Arrange characters alternately
    const res = [];
    let index = 0, max = str.length - 1;
    
    while(keys.length){
        let currKey = keys.shift();
        let count = map[currKey];
        
        while(count){
            res[index] = currKey;
            index = index + 2;
            if(index > max)
                index = 1;
            count--;
        }
    }
    
    return res.join("");
};

console.log(formatString(str));
dad

How It Works

The algorithm places the most frequent character first at even positions (0, 2, 4...), then odd positions (1, 3, 5...). This ensures maximum separation between identical characters. Less frequent characters fill remaining positions using the same pattern.

Edge Cases

// Case where rearrangement is impossible
console.log(formatString('aaa')); // ""

// Case with even length string
console.log(formatString('aabb')); // "abab"

// Single character
console.log(formatString('a')); // "a"

abab
a

Conclusion

This greedy algorithm efficiently rearranges string characters by placing the most frequent characters first at alternating positions. The time complexity is O(n log n) due to sorting, where n is the number of unique characters.

Updated on: 2026-03-15T23:19:00+05:30

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements