However, you can enumerate any two of the three variables, as that number is 500 * 499 = 249,500. Let's focus on a and c. As always, it's best to start with an example, which will help us derive the general case. Suppose our string is "123456789". And suppose that a is 2 and c is 6. We can view our number as follows:
12 3 456 7 89
| | | | |
digits a potential c digits
before b's after
a c
Now, let's take a look at all of the rotations involving a and c:
127356489 or: 12 7 356 4 89 127436589 or: 12 7 436 5 89 127453689 or: 12 7 453 6 89Let's break the sum of these numbers into things that we can compute without needing a loop:
Now, we can compute each of these in constant time, if we precompute the following arrays: