Necklace mirror arcs
HardOnline Assessment
Count the stretches of a circular bead necklace that read the same forwards and backwards.
A necklace is a closed loop of beads. The string beads lists the beads' colours in order around the loop, one lowercase letter per bead, so the last bead is next to the first. A stretch is described by a starting bead i (0 <= i < n, where n is the number of beads) and a length len (1 <= len <= n): it consists of len consecutive beads going in the listed direction from bead i, continuing past the last bead back to bead 0 when needed. A stretch is mirrored when its colours read the same from either end.
Stretches are told apart by their (i, len) pair, so equal-looking stretches at different places are counted separately, and the n stretches of length n (one per starting bead) count as n different stretches. A stretch may not be longer than the necklace, so no bead appears twice in it.
Input:
beads: a non-empty string of lowercase letters.min_len: a positive integer.
Output: an integer, the number of mirrored stretches whose length is at least min_len. If min_len is larger than the number of beads, return 0.
Necklaces can have thousands of beads and repeat colours heavily, so comparing every stretch bead by bead will be too slow.
Example 1
- Input:
- ["aba",1]
- Output:
- 5
- Explanation
- The one-bead stretches give 3. Among two-bead stretches only the one that wraps around from the last bead
ato the first beada(start 2, length 2) is mirrored, whileabandbaare not. Of the three-bead stretches only the one starting at bead 0 (aba) is mirrored. The total is 3 + 1 + 1 = 5.
Example 2
- Input:
- ["abcba",3]
- Output:
- 3
- Explanation
- With
min_len = 3, the mirrored stretches arebcb(start 1, length 3), the whole necklace read from bead 0 (abcba), andbaab(start 3, length 4), which wraps from the last bead around to the first. The answer is 3.
Example 3
- Input:
- ["aaaa",4]
- Output:
- 4
- Explanation
- All beads are the same, so every stretch is mirrored. Only stretches of length 4 count, and there is one for each of the 4 starting beads, so the answer is 4.
Constraints
1 <= beads.length <= 15,000- every character of
beadsis a lowercase letter 1 <= min_len <= 20,000- the answer fits in a 64-bit integer