ProgrammingHardCapgemini · Infosys pattern
What will be the output of the following pseudocode (basic run-length string compression, kept only if actually shorter)?
What will be the output of the following pseudocode (basic run-length string compression, kept only if actually shorter)?
Function compress(String s)
String res = ""
Integer i = 0
while (i < length(s))
Integer j = i
while (j < length(s) and s[j] == s[i])
j = j + 1
end while
res = res + s[i] + toString(j - i)
i = j
end while
if (length(res) < length(s))
return res
end if
return s
End Function
Print compress("aabcccccaaa"), compress("abc")- A. a2b1c5a3 abc
- B. aabcccccaaa abc1c1
- C. a2b1c5a3 a1b1c1
- D. aab1ccccc1aaa abc
Correct answer: A. a2b1c5a3 abc
'aabcccccaaa' compresses to 'a2b1c5a3' (8 chars), shorter than the original 11, so it is returned. 'abc' compresses to 'a1b1c1' (6 chars), which is LONGER than the original 3 characters, so the original 'abc' is kept instead.
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 (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 =…
- What will be the output of the following pseudocode (finding the kth smallest element by sorting)? (Arrays are indexed from 0.) Integer…