All the ways to return 3 if you get 7 and vice versa – interview question

  • A+
Category:Languages

This is a question that I was asked in an interview:
Implement a function that gets an integer n and does the following:
1. if n is 3 -> return 7.
2. else if n is 7 -> return 3.
3. otherwise return any number you like (undefined behavior).

Also describe what's the runtime and space complexity of each way.

So first I gave the trivial way of using if-else statement - and said it's O(1) run-time + space complexity. Then the interviewer said: "what if you can't use if statements (including switch-case and other if statements similarities)?"

So I suggested using bitwise operations: return n^=4. Said that it's O(1) run-time + space complexity. Then the interviewer said: "what if you can't use bitwise operations?"

So I suggested using an array like this:

int mem[8] = {-1, -1, -1, 7, -1, -1, -1, 3};  return mem[n];                

Said it's O(1) run-time + space complexity, how ever it might be non-efficient if we have large numbers instead of 3 and 7.

Then the interviewer said: "what if you can't use arrays?" - and here I got stuck.

It seems like there is a fourth way... any suggestions?

 


how about

def foo(n)   return 10 - n end   foo(3) => 7 foo(7) => 3 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: