Problem 243640 · easy · Level 02 Linear Data Structures

The Banner Hung Backwards

strings · split & join

Strings are immutable in Python: you cannot change a character in place, so string problems are usually solved by building a new string from pieces. The split and join methods are the workhorses.

A sign-maker typed the words of a shop banner into s last word first, and typed carelessly: there may be stray spaces at either end and runs of several spaces between words. Return the words of s in reverse order, with exactly one space between neighbouring words and no space at the start or the end.

Examples

Input:  s = "fresh bread sold here"
Output: "here sold bread fresh"
Input:  s = "  open late  "
Output: "late open"
Explanation: the spaces at both ends are dropped.
Input:  s = "mind   the gap"
Output: "gap the mind"
Explanation: a run of spaces between words becomes a single space.

Constraints

  • 1 <= len(s) <= 10**4
  • s contains letters, digits and spaces, and at least one word

Goals

  • Break a string into words with split() and rebuild it with join()
  • Normalise messy whitespace without character-by-character loops
Starting Python…