Conversation
…ch word in place.
CheezItMan
left a comment
There was a problem hiding this comment.
This solves the problems, but you are not reversing the sentence in place. Consider parsing the string character-by-character and first reversing the whole string, then reversing each word using a modified version of your reversaroo method.
| # Time complexity: ? | ||
| # Space complexity: ? | ||
| # Time complexity: O(n^3) | ||
| # Space complexity: O(n) I believe since there is a second array created in memory to store/reverse each word |
There was a problem hiding this comment.
Yes since you're doing .split it creates a new array, and you create a temp array.
You were asked to reverse the words in place.
| end | ||
|
|
||
|
|
||
| def reversaroo(string, length) |
There was a problem hiding this comment.
Could this method be extended with a start and end index to reverse a substring in place?
| end | ||
|
|
||
| length = my_sentence.length | ||
| reversaroo(my_sentence, length) |
| # first fully reverse the strings | ||
|
|
||
| # take each 'word' and split into an array. then reversaroo the each word and store in an array called word_in_order_array | ||
| split_sentence = my_sentence.split(' ') |
| # take each 'word' and split into an array. then reversaroo the each word and store in an array called word_in_order_array | ||
| split_sentence = my_sentence.split(' ') | ||
| word_in_order_array = [] | ||
| split_sentence.each_with_index do |word, i| |
There was a problem hiding this comment.
O(m * w) where m is the number of words and w the length of the words.
| end | ||
|
|
||
| x = 0 | ||
| word_in_order_array.each do |word| |
| # A method to reverse the words in a sentence, in place. | ||
| # Time complexity: ? | ||
| # Space complexity: ? | ||
| # Time complexity: O(n^3) |
There was a problem hiding this comment.
The time complexity is not O(n3).
Instead you have:
O(n + n + m * w + m)
Since you will have relatively fewer words than letters (where n is the number of letters), and most words will be short, you could say this is O(n) time complexity.
Sorting & Reverse Sentence