Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 691
John Avatar asked Nov 28 '18 15:11

John


3 Answers

how about

def foo(n)
  return 10 - n
end


foo(3) => 7
foo(7) => 3
like image 84
dfens Avatar answered Oct 20 '22 01:10

dfens


How about this

function myfunc(n) {
   return 21 / n
}

console.log(myfunc(7))
console.log(myfunc(3))

UPDATE: #2 Solution

function myfunc(n) {
   return "37".replace(n, "")
}

console.log(myfunc(7))
console.log(myfunc(3))
like image 39
Christhofer Natalius Avatar answered Oct 20 '22 00:10

Christhofer Natalius


Another one is. (n + 4) % 8.

"All the ways" is surely infinite.

like image 24
rici Avatar answered Oct 20 '22 01:10

rici