Splitting a string into maximum parts in JavaScript


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 ]

Updated on: 24-Apr-2021

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements