Okay, I was being interviewed at a company and the interviewer asked me a recursion problem. It was an online interview, so, he had set up the problem statement and a function signature on CodeSandbox (an online code editor/collaboration tool). I was supposed to fill-up the function body. He had only one parameter in the function signature. I added another parameter just to keep track of the result. He said I shouldn't add another parameter(I was providing a default value to the additional parameter), as it changes the function signature.
Now, in my opinion, if you are adding an optional parameter to the signature, it wouldn't make any difference. Let me take a simple example to make it more clear to you:
Problem: Check if the input is a palindrome.
Solution 1:
function isPalindrome(input, index = 0){
const isAMatch = input[index] === input[input.length - 1 - index]
if (index === Math.floor((input.length - 1) / 2)) {
return isAMatch
}
if (isAMatch) {
return isPalindrome(input, ++index)
}
return isAMatch
}
In the solution above, I added an optional parameter: index
to keep track of the index to be matched. The question here is that if it's reasonable to add this optional parameter?
Solution 2:
function isPalindrome(str){
if(str.length === 1) return true;
if(str.length === 2) return str[0] === str[1];
if(str[0] === str.slice(-1)) return isPalindrome(str.slice(1,-1))
return false;
}
In this solution, we aren't using any additional parameters.
Now I'm repeating the question again, would Solution 1 be considered as an invalid solution?
index
parameter should be private and not be exposed to the caller.arguments[1]
. 😉