Finding the power of a string from a string with repeated letters in JavaScript

The power of a string is the maximum length of a non-empty substring that contains only one unique character.

We are required to write a JavaScript function that takes in a string and returns its power.

For example ?

const str = "abbcccddddeeeeedcba"

Then the output should be 5, because the substring "eeeee" is of length 5 with the character 'e' only.

How It Works

The algorithm traverses the string and counts consecutive identical characters. It tracks the maximum count found, which represents the power of the string.

String: "abbcccddddeeeeedcba" a 1 b 2 b c 3 c c d 4 d d d e 5 e e e e e d c b a Maximum consecutive length: 5 (eeeee) Power of string = 5

Example

The code for this will be ?

const str = "abbcccddddeeeeedcba"
const maxPower = (str = '') => {
    let power = 1
    const sz = str.length - 1
    for(let i = 0; i 

Output

And the output in the console will be ?

5

Alternative Approach

Here's a cleaner implementation that's easier to understand:

const findStringPower = (str) => {
    if (!str || str.length === 0) return 0;
    
    let maxPower = 1;
    let currentPower = 1;
    
    for (let i = 1; i 

5
1
4
0

Conclusion

The power of a string is found by identifying the longest sequence of consecutive identical characters. Both approaches work efficiently with O(n) time complexity, scanning the string once to find the maximum consecutive character count.

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

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements