ProgrammingHardAccenture · Cognizant pattern
What will be the output of the following pseudocode (counting permutations of a string via recursion)?
What will be the output of the following pseudocode (counting permutations of a string via recursion)?
Function countPerms(String s)
if (length(s) <= 1)
return 1
end if
return length(s) * countPerms(substring(s, 1))
End Function
Print countPerms("abcd")- A. 10
- B. 16
- C. 20
- D. 24
Correct answer: D. 24
This computes n! via recursion: length(s)=4 multiplied by countPerms of the remaining 3-character string, unwinding to 4*3*2*1 = 24.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode (basic run-length string compression, kept only if actually shorter)? Function…
- What will be the output of the following pseudocode (counting distinct substrings of length 2)? String s = "abab" Set subs = empty set for…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division.) Integer n = 20, steps = 0…
- What will be the output of the following pseudocode (counting all subsets of a set of size n)? Function countSubsets(Integer n) if (n ==…
- What will be the output of the following pseudocode (counting set bits using Brian Kernighan's trick, for each value 0 to 7)? (& is…
- What will be the output of the following pseudocode (longest common prefix of a list of strings)? Function lcp(List strs) String prefix =…