Javascript Program to Minimize Characters to be Changed to make the Left and Right Rotation of a String Same

In this problem, we need to find the minimum number of character changes required to make a string's left and right rotations identical. This involves understanding how rotations work and finding patterns in character positioning.

Understanding Rotations

The left rotation moves characters left by one position, while right rotation moves them right. For rotations to be identical, specific character patterns must exist:

  • Odd length strings: All characters must be the same

  • Even length strings: Characters at even positions must be identical, and characters at odd positions must be identical

Problem Analysis

Given a string of size N, we need to determine the minimum cost to make left and right rotations identical by changing characters. Each character change costs 1.

Examples

Example 1: str = "tut"

Output: 1

Explanation: Odd length requires all characters to be same. Change 'u' to 't' ? "ttt"

Example 2: str = "gggggggggggg"

Output: 0

Explanation: All characters are already identical

Example 3: str = "mpmntrmnfdmn"

Output: 5

Explanation: Even length - make even positions all 'm' and odd positions all 'n'

Algorithm

The approach differs based on string length parity:

For even length:

  1. Count frequency of characters at even and odd positions separately
  2. Find most frequent character at even positions
  3. Find most frequent character at odd positions
  4. Calculate changes needed for remaining positions

For odd length:

  1. Count frequency of all characters
  2. Find most frequent character
  3. Calculate changes needed for remaining positions

Implementation

function findMinCharacters(str) {
    const str_size = str.length;
    let minCost = str_size;
    
    if (str_size % 2 === 0) {
        // Even length string
        const evenFreq = new Array(128).fill(0);
        const oddFreq = new Array(128).fill(0);
        
        // Count frequencies at even and odd positions
        for (let i = 0; i < str_size; i++) {
            if (i % 2 === 0) {
                evenFreq[str[i].charCodeAt(0)]++;
            } else {
                oddFreq[str[i].charCodeAt(0)]++;
            }
        }
        
        // Find maximum frequencies
        let maxEven = Math.max(...evenFreq);
        let maxOdd = Math.max(...oddFreq);
        
        // Calculate minimum changes needed
        minCost = str_size - maxEven - maxOdd;
    } else {
        // Odd length string
        const charFreq = new Array(128).fill(0);
        
        // Count frequency of each character
        for (let i = 0; i < str_size; i++) {
            charFreq[str[i].charCodeAt(0)]++;
        }
        
        // Find maximum frequency
        let maxFreq = Math.max(...charFreq);
        
        // Calculate minimum changes needed
        minCost = str_size - maxFreq;
    }
    
    return minCost;
}

// Test cases
console.log("Test 1 - 'tut':", findMinCharacters("tut"));
console.log("Test 2 - 'gggggggggggg':", findMinCharacters("gggggggggggg"));
console.log("Test 3 - 'mpmntrmnfdmn':", findMinCharacters("mpmntrmnfdmn"));
Test 1 - 'tut': 1
Test 2 - 'gggggggggggg': 0
Test 3 - 'mpmntrmnfdmn': 5

Complexity Analysis

Aspect Complexity Explanation
Time O(N) Single pass through string of length N
Space O(1) Fixed size arrays (128 characters)

How It Works

The solution leverages the mathematical property that for rotations to be identical, characters must follow specific patterns. By finding the most frequent characters in required positions, we minimize the number of changes needed.

Conclusion

This problem demonstrates how mathematical observations can simplify complex rotation problems. The key insight is recognizing that identical rotations require predictable character patterns based on string length parity.

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

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements