https://leetcode.com/problems/reverse-words-in-a-string-ii/description/

Tag: Array/List

Key Point:

  1. Reverse the whole string then reverse each individual word
  2. xCorrectly Handle the first and last word

Solution:

class Solution:
	def reverseWords(self, s: List[str]) -> None:
        s.reverse()
        space_indexes = (idx for idx in range(len(s)) if s[idx] == ' ')
        last = -1
        for idx in space_indexes:
            s[last+1:idx] = reversed(s[last+1:idx])
            last = idx
        s[last+1:] = reversed(s[last+1:])

Note:

Generator Expression lazily yield elements so takes O(1) space.

ListComp/DictComp/SetComp takes O(n) space

SetComp doesn’t preserve order while DictComp and ListComp does