# LeetCode: Number of Ways to Split a String Solution

*Playing with indexes*

## Approach

Calculate number of ones and store their indexes

If number of ones is not divisible by 3, then the result is 0

If number of ones is 0, then the result is combination of string's length minus 1, taken 2

100000023string length of 645we have 5 possible position to place dividers, but we only need to place 2 dividers67so the result will be the combination of 2-divider selected in 5 possibilities

In the normal case, the result will be the possibilities of placing dividers in the first and the last gaps

1s = 1 0 0 1 0 0 0 1 0 1 0 0 1 1 02i = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 143i1 = 0 _ _ 3 _ _ _ 7 _ 9 _ _ 12 13 _45to maintain size of the splits, we could place any dividers between 2 gaps:6- (3, 7) - 4 possibilities7- (9, 12) - 3 possibilities8so the result will be 4 * 3 = 12

## Implementation

1var numWays = function (s) {2 const MOD = 1e9 + 73 const idxOfOnes = s4 .split("")5 .map((char, idx) => [char, idx])6 .filter(([char, idx]) => char === "1")7 .map(([char, idx]) => idx)89 if (idxOfOnes.length % 3 !== 0) return 010 if (idxOfOnes.length === 0)11 return (((s.length - 1) * (s.length - 2)) / 2) % MOD1213 const firstGapEnd = idxOfOnes.length / 314 const firstGapStart = firstGapEnd - 115 const secondGapEnd = firstGapEnd * 216 const secondGapStart = secondGapEnd - 11718 return (19 ((idxOfOnes[firstGapEnd] - idxOfOnes[firstGapStart]) *20 (idxOfOnes[secondGapEnd] - idxOfOnes[secondGapStart])) %21 MOD22 )23}

## References

## Similar problems

Split Array with Equal Sum

## Comments

Loading comments...

## Tags

leetcode

math

string

## Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

**Fact corner:** Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

**Still hesitate?** Read HoningJS author's guide on dealing with Toptal interview process.