Splitting a string into maximum parts in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string, str, as the first and the only argument.

The purpose of our function is to partition this string into as many parts as possible so that each letter appears in at most one part, and return an array of integers representing the size of these parts.

For example, if the input to the function is

Input

const str = "ababcbacadefegdehijhklij";

Output

const output = [9, 7, 8];

Output Explanation

The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits string str into less parts.

Example

Following is the code −

 Live Demo

const str = "ababcbacadefegdehijhklij";
const splitStrings = (str = '') => {
   const res = []
   const map = {}
   for (let i = 0; i < str.length; i++) {
      map[str[i]] = i
   }
   let start = 0
   while (start <= str.length - 1) {
      let end = map[str[start]]
      for (let i = start + 1; i < end; i++) {
         const currentEnd = map[str[i]]
         if (currentEnd > end) {
            end = currentEnd
         }
      }
      res.push(end - start + 1)
      start = end + 1
   }
   return res
};
console.log(splitStrings(str));

Output

[ 9, 7, 8 ]
raja
Published on 24-Apr-2021 10:03:16
Advertisements