Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reverse Words - Hannah #24

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Conversation

hertweckhr1
Copy link

No description provided.

@hertweckhr1
Copy link
Author

hertweckhr1 commented Sep 18, 2018

Time Complexity: n^2
Space Complexity: o(n)
-as array increases in size, number of variables stays the same, but new_string variable will increase in length as my_words gets larger)

@@ -21,7 +21,7 @@ def reverse_words(my_words)
my_words.length.times do |x|
my_words[x] = new_string[x]
end

return my_words

Choose a reason for hiding this comment

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

Since you're updating the characters in the input parameter my_words in place, you don't need to return anything. Line 24 could simply be return.

Choose a reason for hiding this comment

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

Ditto with line 42

@shrutivanw
Copy link

Good work!

You determined the space complexity correctly for your algorithm. Think through whether you can think of another approach that does not require creating a new string and hence needing O(n) space.

The time complexity of your algorithm is O(n). You go through each character in the input string in the first loop. Once a word boundary is determined, that word gets reversed. Imagine a scenario where there is only one word in the input starting at index 0 and ending at index length-1. In this case, to determine the beginning and end of the word, will need n steps. After that (and hence addition), reversing the whole word would take n/2 steps. Leading to a time complexity of O(n + n/2) = O(n)
If there are only white spaces in the input, then reverse will never get called and the first times loop will run n times. Leading to O(n) time complexity.
In either case, at the end, you copy over each character from the new string back to the input parameter string needing O(n) time.

Take a look at my solution with O(n) time and O(1) space complexity: https://github.com/Ada-C10/reverse_words/blob/solution/lib/reverse_words.rb

Slack me if you have any questions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants