Reverse Words in a String⚓︎
- Reverse Words in a String
- Description
- Solution
Description⚓︎
Given an input string s
, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s
will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
- Input:
s = "the sky is blue"
- Output:
"blue is sky the"
Example 2:
- Input:
s = " hello world "
- Output:
"world hello"
- Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
- Input:
s = "a good example"
- Output:
"example good a"
- Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Constraints:
1 <= s.length <= 10^4
s
contains English letters (upper-case and lower-case), digits, and spaces' '
.- There is at least one word in
s
.
Solution⚓︎
Original Solution Using Library Functions⚓︎
Code⚓︎
Full testing code:
iss >> word
is an extraction operation that reads data from iss
and stores it in word
. It automatically splits the input based on whitespace (spaces, tabs, newlines).
Detailed complexity analysis⚓︎
Overall Time Complexity Analysis⚓︎
- Trimming Spaces:
- The functions
find_first_not_of
andfind_last_not_of
both run in linear time, \(O(N)\), where \(N\) is the length of the strings
. - The
substr
operation is also \(O(N)\), as it potentially needs to copy the entire string. - Splitting the String into Words:
- The
istringstream
constructor and the loop that reads words both operate in \(O(N)\) time. Each character is read and processed once to split the string into words. - Reversing the Words:
- The
reverse
function operates in \(O(\frac{W}{2})\), where W is the number of words. In terms of Big O notation, this simplifies to \(O(W)\). - Concatenating the Words:
- The loop for concatenating words runs in \(O(W)\), as it iterates over all words. However, the string concatenation inside the loop (
result += words[i]
) has its own complexity. In the worst case, each concatenation can be \(O(N)\) due to potential reallocation and copying of the entire string. Thus, this step could be as bad as \(O(WN)\).
Overall Space Complexity Analysis⚓︎
- Additional String Storage:
- The
substr
operation creates a new string, which is \(O(N)\) in space. - Storing Words:
- The
vector<string>
words
stores each word separately. In the worst case, if the string is composed entirely of single-character words separated by spaces, the number of words will be approximately \(\frac{N}{2}\) (every other character is a space), leading to a space complexity of \(O(N)\). - Intermediate String Storage:
- The
result
string, in the worst case, will hold the entire input string in reverse order, which is \(O(N)\).
Summarization: Complexity of C++ Standard Library Functions⚓︎
find_first_not_of
,find_last_not_of
: \(O(N)\)substr
: \(O(N)\) for copying the substring.istringstream
: The construction is \(O(N)\) as it copies the string.istringstream::operator>>
: \(O(N)\) overall for reading the entire string.vector::push_back
: Amortized \(O(1)\) for each call, but can lead to occasional resizing, which is \(O(N)\) for that operation.reverse
: \(O(\frac{W}{2})\) which simplifies to \(O(W)\).- String concatenation (
+=
): \(O(N)\) in the worst case for each operation due to potential reallocation and copying.
The overall time complexity of the implementation is dominated by the string splitting and concatenation steps, both of which can approach \(O(N^2)\) in the worst case due to the way strings are handled in C++. The space complexity is primarily \(O(N)\), driven by the storage of the words and the final result string.
Solution Implementing the Function Ourselves⚓︎
Way 1⚓︎
The entire string is reversed first, and then each word is reversed back internally.
- Time complexity: \(O(n)\);
- Space complexity: \(O(1)\) for C++.
Way 2 (Recommended)⚓︎
Flip each word internally first, then reverse the entire string back.
Python Solution⚓︎
Function Breakdown⚓︎
s.strip()
:strip()
is a string method in Python that removes any leading and trailing whitespace (including spaces, newlines, and tabs) from the strings
.- For instance,
" hello world ".strip()
would result in"hello world"
. split()
:split()
is a method that divides a string into a list of substrings, separated by the specified separator. By default, it splits based on any whitespace and removes it.- For example,
"hello world".split()
results in["hello", "world"]
. [::-1]
:- This is a slicing operation that reverses the list.
[::-1]
means start at the end of the list and end at position 0, move with the step -1 (one step backward). - For a list
["hello", "world"]
, the result of[::-1]
would be["world", "hello"]
. ' '.join(...)
:join()
is a string method used to join elements of an iterable (like a list) into a single string, with the specified string as a separator. Here, it uses a space' '
as the separator.- For example,
' '.join(["world", "hello"])
would result in"world hello"
.
Putting it all together, this one-liner first removes leading and trailing spaces from the input string, splits the string into words, reverses the list of words, and then joins them back into a single string with spaces in between.
Time Complexity Analysis⚓︎
- Strip Operation: \(O(N)\), where \(N\) is the length of the string. This is because it potentially needs to check each character at both ends of the string.
- Split Operation: \(O(N)\), as it goes through the entire string to split it into words.
- List Reversal: \(O(W)\), where \(W\) is the number of words in the string. This is typically considered a linear operation with respect to the number of elements in the list.
- Join Operation: \(O(N)\), as it has to combine all the words back into a single string.
The overall time complexity of the function is \(O(N)\), as each character in the string is processed a constant number of times.
Space Complexity Analysis⚓︎
Intermediate Lists and Strings: The space complexity is mainly due to the storage of the split words and the final string. This would be \(O(N)\), as in the worst case, the number of words and the total length of the words (including the spaces in the final joined string) can be proportional to the length of the original string.