Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions lib/reverse_sentence.rb
Original file line number Diff line number Diff line change
@@ -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.
Comment on lines +2 to +3

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well done


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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very good helper method

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

18 changes: 15 additions & 3 deletions lib/sort_by_length.rb
Original file line number Diff line number Diff line change
@@ -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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nicely done insertion sort.

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
File renamed without changes.