diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..e23ce80 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -1,6 +1,35 @@ # A method to reverse the words in a sentence, in place. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n), because we check at most 2 times each character. +# Space complexity: O(1), variables are always constant. + def reverse_sentence(my_sentence) - raise NotImplementedError + if my_sentence == nil + return my_sentence + end + + reverse(my_sentence, 0, my_sentence.length - 1) + index = 0 + first = 0 + my_sentence.each_char do |character| + if character == " " + reverse(my_sentence, first, index - 1) + first = index + 1 + end + index += 1 + end + reverse(my_sentence, first ,my_sentence.length - 1) end + +def reverse(string,first,last) + memo = 0 + i = first + j = last + while i < j + memo = string[i] + string[i] = string[j] + string[j] = memo + i += 1 + j -= 1 + end +end + diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..b44d3a9 100644 --- a/lib/sort_by_length.rb +++ b/lib/sort_by_length.rb @@ -1,7 +1,19 @@ # A method which will return an array of the words in the string # sorted by the length of the word. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n^2) as there are two loops that depend on the size of the elements. +# Space complexity: O(n) as I'm creating a new array. def sort_by_length(my_sentence) - raise NotImplementedError, "Method not implemented" + my_sentence = my_sentence.split(" ") + i = 1 + while i < my_sentence.length + to_insert = my_sentence[i] + j = i + while j > 0 && my_sentence[j-1].length > to_insert.length + my_sentence[j] = my_sentence[j-1] + my_sentence[j-1] = to_insert + j -= 1 + end + i += 1 + end + return my_sentence end diff --git a/test/sort_by_length.rb b/test/sort_by_length_test.rb similarity index 100% rename from test/sort_by_length.rb rename to test/sort_by_length_test.rb