Rearrange string so that same character become n distance apart JavaScript

We need to rearrange a string so that identical characters are exactly n positions apart from each other. This problem requires careful character placement to maintain the specified distance constraint.

For example, if we have the string "accessories" and n = 3, we need to ensure that each 's' character is exactly 3 positions away from other 's' characters, and the same applies to other repeated characters.

Problem Understanding

The algorithm works by:

  • Counting the frequency of each character
  • Sorting characters by frequency (most frequent first)
  • Placing characters in a round-robin fashion with n distance apart

Implementation

const str = 'accessories';

const equalDistance = (str, num) => {
    // Count frequency of each character
    const map = str.split("").reduce((acc, val) => {
        const count = acc.get(val);
        if(typeof count === 'number'){
            acc.set(val, count + 1);
        } else {
            acc.set(val, 1);
        }
        return acc;
    }, new Map());
    
    // Sort characters by frequency (descending)
    const arr = Array.from(map).sort((a, b) => b[1] - a[1]);
    let newString = '';
    
    // Place characters with n distance apart
    for(let i = 0, count = 0; i < str.length;){
        if(!arr[count][1]){
            arr.splice(count, 1);
            continue;
        }
        newString += arr[count][0];
        arr[count][1]--;
        i++;
        count = i % num;
    }
    
    return newString;
};

// Test the function
console.log(equalDistance(str, 4));
console.log(equalDistance('abb', 2));
console.log(equalDistance('aacbbc', 3));
sceasceosri
bab
acbacb

How It Works

The algorithm uses a round-robin approach:

  1. Character Counting: Creates a frequency map of all characters
  2. Sorting: Sorts characters by frequency to prioritize placement of most frequent characters
  3. Placement: Uses modulo operation (i % num) to cycle through positions, ensuring n-distance separation

Example Walkthrough

// For string "aacbbc" with n=3:
// Character frequencies: a=2, c=2, b=2
// Placement positions: 0, 1, 2, 0, 1, 2
// Result: "acbacb" - each character is 3 positions apart

const testStr = 'aacbbc';
console.log(`Original: ${testStr}`);
console.log(`Rearranged with n=3: ${equalDistance(testStr, 3)}`);

// Verify the distance
const result = equalDistance(testStr, 3);
console.log(`First 'a' at position 0, second 'a' at position 3 - distance: 3`);
Original: aacbbc
Rearranged with n=3: acbacb
First 'a' at position 0, second 'a' at position 3 - distance: 3

Key Points

  • The algorithm prioritizes characters with higher frequency to ensure successful placement
  • Multiple valid solutions may exist - the order depends on the sorting and placement strategy
  • The distance n must be smaller than the string length for the algorithm to work effectively
  • Characters with the same frequency may appear in different orders in the final result

Conclusion

This solution effectively rearranges strings to maintain n-distance separation between identical characters using frequency counting and round-robin placement. The approach ensures optimal character distribution while handling multiple character frequencies.

Updated on: 2026-03-15T23:18:59+05:30

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements