Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Reverse the order of words in a sentence, collapsing multiple spaces.

Problem: Reverse the order of words in a sentence, collapsing multiple spaces.
s = "  the  sky is   blue "
print("|" + " ".join(reversed(s.split())) + "|", len(s.split(" ")))
What is printed?
  1. A. |blue is sky the| 4
  2. B. | blue is sky the | 10
  3. C. |blue is sky the| 10
  4. D. |blue is sky the| 10

Correct answer: C. |blue is sky the| 10

split() with no argument splits on runs of whitespace and drops empty strings, so the words are the, sky, is, blue. split(" ") splits on every single space and keeps empty strings: 10 pieces. Interviewers check that you handle leading, trailing and repeated spaces.

More Coding Interview Problems questions

Exams that ask this topic