Write a function which accepts a string consisting only of A, B, X and Y, and returns a maximum number of possible pairwise connection that can be made.
Here's the catch -- you need to follow the rules below:
- You can connect A with B or B with A or X with Y or Y with X.
- Each letter can participate in such connection only once.
- Connections must all be done in the same direction.
- Connections must not intersect.
Example
B X A B A Y B A
| |_| | |_|
|_______|
No matter how you connect A to B and X to Y (without intersecting), you will only be able to make three connections in this example, so the answer for connect(BXABAYBA) is 3.
Tests
connect("BXABAYBA")
connect("AAAAAAAA")
connect("ABABABAB")
connect("BABBYYAYAAB")
This challenge comes from smiks on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (1)
Rust
A brute force approach, by recursing and treating the three parts each "bracket" splits the input into as separate inputs (since they can never interact).
A lot of typical optimizations could be possible, such as memoizing on range, or memoizing on pattern (and compressing the pattern to 2 characters per byte for the hash), but this might be slower.
However, a better optimization would be based on some topological insight, for example that we don't need to ever pick a smaller bracket if that doesn't release a different (or keep track of necessary?) letter to the outside.
(eg.
AXABYYBdoesn't need to beaXabYyb, onlyaXabyYb,AXABYXYBdoesn't need to beaXabYxyb, onlyaXabyxYb(yxcan now match inside, inmidpart))Or some other observation of the sort.
Look at it go!
Version history:
Ver 1
Iterator::maxfor inner iteratorInitial