DEV Community

Aastha Talwaria
Aastha Talwaria

Posted on

Let's split and count

Given a string of letters and we have to find the number of times the string can be splitted in such a way that atleast one the splitted string have equal number of occurance of x and y.


Example:
Let's say string is ayxbx. So possible case are:

  • a and yxbx
  • ay and xbx
  • ayx and bx
  • ayxb and x

Out of these possible cases only 2nd case (ay and xbx) does not satisfy the condition.(ay has 1 'y's and 0 'x's, xbx` has 0 'y's and 2 'x's).


My Approach:

  • Split and count
    `

    function getCount (str){ let strLength = str.length; if(strLength < 2){ return 0; } let count = 0, firstStringLettersCount = { x: 0, y:0 }, secondStringLettersCount = { x: 0, y:0 }; for(let i = 0; i < strLength; i++){ secondStringLettersCount[str[i]] += 1; } for(let i = 0; i < strLength-1 ; i++){ firstStringLettersCount[str[i]] += 1; secondStringLettersCount[str[i]] -= 1; if( firstStringLettersCount['x'] === firstStringLettersCount['y'] || secondStringLettersCount['x'] === secondStringLettersCount['y'] ){ count++; } } return count; } 


    `

Top comments (0)