Encoding string based on character frequency in JavaScript

We are required to write a JavaScript function that takes in a string as an argument and creates a new string based on character frequency. Each character in the new string is '(' if that character appears only once in the original string, or ')' if that character appears more than once. The comparison should be case-insensitive.

Problem Statement

Given a string, encode each character as:

  • '(' - if the character appears only once
  • ')' - if the character appears more than once
  • Ignore case when counting character frequency

For example, if the input is "Success", the output should be ")())())" because:

  • 'S' appears twice ? ')'
  • 'u' appears once ? '('
  • 'c' appears twice ? ')'
  • 'c' appears twice ? ')'
  • 'e' appears once ? '('
  • 's' appears twice ? ')'
  • 's' appears twice ? ')'

Solution

The approach involves two passes through the string: first to count character frequencies, then to build the encoded string.

const str = 'Success';

const mapString = (str = '') => {
    const mainStr = str.toLowerCase();
    const hash = {};
    let res = '';
    
    // First pass: count character frequencies
    for (let char of mainStr) {
        hash[char] = (hash[char] || 0) + 1;
    }
    
    // Second pass: build encoded string
    for (let char of mainStr) {
        if (hash[char] > 1) {
            res += ')';
        } else {
            res += '(';
        }
    }
    
    return res;
};

console.log(mapString(str));
console.log(mapString('Hello World'));
console.log(mapString('abcdef'));
)())())
)((()()((()(
((((((

How It Works

The algorithm follows these steps:

  1. Convert to lowercase: Ensures case-insensitive comparison
  2. Count frequencies: Use a hash map to store character counts
  3. Encode characters: Replace each character with '(' or ')' based on its frequency

Alternative Implementation

Here's a more concise version using modern JavaScript features:

const encodeString = (str) => {
    const lowerStr = str.toLowerCase();
    const charCount = {};
    
    // Count frequencies
    [...lowerStr].forEach(char => {
        charCount[char] = (charCount[char] || 0) + 1;
    });
    
    // Encode string
    return [...lowerStr].map(char => charCount[char] > 1 ? ')' : '(').join('');
};

console.log(encodeString('Success'));
console.log(encodeString('Programming'));
)())())
))()))))()(

Conclusion

This character frequency encoding technique uses a two-pass algorithm: first counting character frequencies in a hash map, then encoding each character based on whether it appears once or multiple times. The case-insensitive comparison ensures consistent results regardless of input capitalization.

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

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements