4

I had an interview and I was not able to give a best approach for the problem.

A=1, B=0
- Operation L: A=2A-B
- Operation R: B=2B-A

For each step, only one operation(L or R) is taken place.

For a given number N, what is the minimum number of operations required to make A or B equals to N?

The most important one is an efficiency.

Thanks in advance.

גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61
Ming Soon
  • 998
  • 2
  • 11
  • 32

2 Answers2

4

In k operations you can get all values of N in [-(2^k)+1, 2^k].

Notice that abs(A) + abs(B) = 2^k for all possible k paths, and that A & B exactly cover the range [-(2^k)+1, 2^k] in the set of paths of length k.

k=0: (1,0)
k=1: (1,-1), (2,0)
k=2: (1,-3), (2,-2), (3,-1), (4,0)
etc...

Given N we can find the minimum k via log. Then we know the final pair is (N, N - 2^k) (or (N-2^k, N) if N <= 0). It's easy to follow the path back up to k=0 because one of the two elements will be out of range for the next smaller k.

E.g., N = 35.

Log2(35) = 5.13, so we use k=6.
2^6 = 64, so our final pair is (35, -29)
(35,-29) -> (3,-29) -> (3, -13) -> (3, -5) -> (3,-1) -> (1,-1) -> (1,0)

Figuring out k is O(1), finding the path is O(k) which is O(log(abs(N)).

It's not likely you need to prove anything in an interview, but if you did, you could use this:

By observation: A - B = 2^k for k steps observed for small k.

Then via induction: we have some valid (A, B) s.t. A-B = 2^k. Then L gets us (2A-B, B), but 2A-B-B = 2A-2B = 2(A-B) = 2^(k+1) as desired. Similarly for R.

Dave
  • 7,460
  • 3
  • 26
  • 39
  • *"Notice that abs(A) + abs(B) = 2^k for all possible k paths"* - this seems like a very unsuitable interview question, if the solution is to pull this rabbit out of a hat. – kaya3 Mar 12 '21 at 07:57
  • @kaya3 I'm guessing the interviewer would be satisfied with the candidate noticing that everything between -(2^k)+1, 2^k is reachable in k steps and accepting that without proof. – Dave Mar 12 '21 at 11:49
  • @kaya3 There does seem to be a [simple logical assessment](https://stackoverflow.com/a/66614354/2034787) we can make that doesn't require sampling steps, although I wouldn't think it easy in an interview setting. – גלעד ברקן Mar 13 '21 at 15:02
0

It would be a challenging task for an interview but I would start with the recursion of trying to find the origin from the result. Given valid (A', B), where A' is the target we are after,

A' = 2A - B

for some A, which means that

A = (A' + B) / 2

The latter tells us that all (A' + B) in the path must be divisible by 2, and since the path ends (starts) at 1, all the (A' + B) in it are powers of 2.

Another property we can observe, although it may not be relevant to the solution is that once we switch in the first step to (even, even) or (odd, odd), we cannot switch back.

גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61