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
27 changes: 24 additions & 3 deletions lib/reverse_sentence.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,27 @@
# A method to reverse the words in a sentence, in place.
# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n)
# Space complexity: O(n)

Choose a reason for hiding this comment

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

You were requested to do this in-place, so without creating a new array.

# Not pleased with how regex captures the whitespaces and think that it creates unneccesary iteration for the program to run. I couldn't figure a better one out though.

def reverse_sentence(my_sentence)
raise NotImplementedError
if my_sentence == nil
return nil
end

my_sentence_array = my_sentence.split(/(\S+|\s{1,})/)
length = my_sentence_array.length
index = 0
temp = 0

while index < length / 2
temp = my_sentence_array[index]
my_sentence_array[index] = my_sentence_array[length - index - 1]
my_sentence_array[length - index - 1] = temp
index += 1
end

reversed_sentence = my_sentence_array.join('')
my_sentence[0..my_sentence.length] = reversed_sentence

end

25 changes: 19 additions & 6 deletions lib/sort_by_length.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
# 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)
# Space complexity: O(n)
Comment on lines +1 to +2

Choose a reason for hiding this comment

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

Correct space complexity is correct since you have to split the string.

def sort_by_length(my_sentence)
raise NotImplementedError, "Method not implemented"
end
my_sentence_array = my_sentence.split(' ')
length = my_sentence_array.length
i = 1

while i < length
to_insert = my_sentence_array[i]
j = i

while j > 0 && my_sentence_array[j-1].length > to_insert.length
my_sentence_array[j] = my_sentence_array[j - 1]
j -= 1
end
my_sentence_array[j] = to_insert
i += 1
end
return my_sentence_array
end