Very short solution (somewhat inefficient).
Small simplification of main case.
Testcases and solutions.