Skip to content Skip to sidebar Skip to footer

Javascript Algorithms: Find Starting And Ending Indices Of Consecutively Repeated Chars From A String

I wanted to function a function that does this: const input =“hellooooloo”; const results = getRepeated(input); console.log(results) // [(2,3), (4,7), (9,10)] It returns an ar

Solution 1:

I'd use a regular expression: match and capture one character, then backreference that same character as many times as you can. Perform a global regex match on the string. Take all the matches and map them to an array of their index, and their index plus the length of the match:

constgetRepeated = str => [...str.matchAll(/(.)\1+/g)]
  .map(({ index, 0: match }) => [index, index + match.length - 1]);

const input = "hellooooloo";
const results = getRepeated(input);
console.log(results) // [(2,3), (4,7), (9,10)]

This is O(n).

The regular expression means:

  • (.) - Match any character, put it in a capture group
  • \1+ - Repeat the same character matched by that capture group one or more times

Eg, for the example input here, you'll get the following matches:

[
  { 0: 'll', 1: 'l', index: 2 },
  { 0: 'oooo', 1: 'o', index: 4 },
  { 0: 'oo', 1: 'o', index: 9 },
]

Solution 2:

You couldr educe the array of characters and check if the last character is equal to the actual and adjust the second index of the last index pair.

Otherwise check if the actual character is equal to the next character and create a new result set.

constgetRepeated = ([...array]) => array.reduce((r, c, i, a) => {
        if (a[i - 1] === c) r[r.length - 1][1] = i;
        elseif (c === a[i + 1]) r.push([i]);
        return r;
    }, []),
    input = 'hellooooloo',
    result = getRepeated(input); // [[2, 3], [4, 7], [9, 10]]console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Post a Comment for "Javascript Algorithms: Find Starting And Ending Indices Of Consecutively Repeated Chars From A String"