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")
  1. A. a2b1c5a3 abc
  2. B. aabcccccaaa abc1c1
  3. C. a2b1c5a3 a1b1c1
  4. 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.

More Pseudocode and Code Tracing questions

Exams that ask this topic