Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Compress a string by replacing each run with the letter followed by the run length (only when the run is longer than 1).
Problem: Compress a string by replacing each run with the letter followed by the run length (only when the run is longer than 1).
def compress(s):
out, i = [], 0
while i < len(s):
j = i
while j < len(s) and s[j] == s[i]:
j += 1
out.append(s[i] + (str(j - i) if j - i > 1 else ''))
i = j
return ''.join(out)
print(compress("aaabccddddddddddde"))What is printed?- A. a3bc2d11e
- B. a3b1c2d11e1
- C. a3bc2d1e
- D. a3bc2d10e
Correct answer: A. a3bc2d11e
Runs: aaa → a3, b → b, cc → c2, eleven d's → d11, e → e. The run length can exceed 9, so it must be written with str(), not as a single digit character (which gives the d1 trap). O(n).
More Coding Interview Problems questions
- Problem: Reverse the order of words in a sentence, collapsing multiple spaces. python s = " the sky is blue " print("|" + "…
- Problem: Find the first non-repeating character in a string of lowercase letters; return its index or −1. java static int…
- Problem: Check whether s2 contains a permutation of s1 as a substring. python def hasperm(s1, s2): k = len(s1) need = [0] 26; win = [0] 26…
- Problem: Return the longest common prefix of a list of file paths. python def lcp(words): if not words: return "" p = words[0] for w in…
- Problem: Compute the minimum number of characters to add at the end of s so that it becomes a palindrome, using the KMP prefix function…
- Problem: Search a pattern of length m in a text of length n = 10⁶ (m up to 10⁵) and report all match positions. Which method guarantees…