ProgrammingHardAccenture · Cognizant pattern
What will be the output of the following pseudocode (longest common prefix of a list of strings)?
What will be the output of the following pseudocode (longest common prefix of a list of strings)?
Function lcp(List strs)
String prefix = strs[0]
for (each s in strs, skipping the first)
while (not startsWith(s, prefix))
prefix = prefix[0 .. length(prefix) - 2]
if (length(prefix) == 0)
return ""
end if
end while
end for
return prefix
End Function
Print lcp({"flower", "flow", "flight"})- A. fl
- B. flo
- C. f
- D. flow
Correct answer: A. fl
Starting with prefix='flower', it shrinks against 'flow' (common prefix becomes 'flow'), then shrinks further against 'flight' (common prefix becomes 'fl', since 'flow' doesn't match 'flight' beyond 'fl').
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 (finding the kth smallest element by sorting)? (Arrays are indexed from 0.) Integer…
- What will be the output of the following pseudocode (number of ways to climb n stairs, taking 1 or 2 steps at a time)? Function…
- What will be the output of the following pseudocode (product of array except self, without using division)? (Arrays are indexed from 0.)…
- What will be the output of the following pseudocode (how many output rows a zigzag string conversion uses)? Function numRowsUsed(String s…
- What will be the output of the following pseudocode (counting islands in a grid using flood-fill DFS)? (Grids are indexed from 0.) Integer…
- What will be the output of the following pseudocode (summing positive and negative matrix entries separately)? Integer mat[3][3] = {{1…