Pattern visualizer
Reverse Words in a String
Two problems are hiding in one here, and mixing them is what makes this question fiddly. The first is spacing: a raw split on a space leaves an empty token wherever spaces were doubled, or at the very start and end of the string. Throw those away and the messy input becomes a clean list of words. The second is the reversal itself, which is now the ordinary two-pointer swap: one pointer at each end, trade the two words, step inward. Once the pointers meet, everything is already in place, and joining with a single space cannot reintroduce the spacing mess because the blanks were dropped before the reversal ever started. Animated on: s = " the sun is not up yet " — reverse the order of the words, collapsing every run of spaces down to one and dropping the leading and trailing ones..
Split away the blanks, then swap from both ends inward
Splitting " the sun is not up yet " on a single space gives 10 tokens, and 4 of them are empty — one for every leading, trailing or doubled space. Those blanks are not words.
1FUNCTION reverseWords(s):2 words <- EMPTY LIST3 FOR EACH token IN SPLIT(s, " "):4 IF token != "":5 APPEND token TO words6 l <- 07 r <- LENGTH(words) - 18 WHILE l < r:9 SWAP words[l] AND words[r]10 l <- l + 111 r <- r - 112 RETURN JOIN(words, " ")
← / → step · space play · Home restart