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
36 changes: 27 additions & 9 deletions lib/recursive-methods.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
# Authoring recursive algorithms. Add comments including time and space complexity for each method.

# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n)
# Space complexity: O(n)
def factorial(n)

Choose a reason for hiding this comment

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

👍

raise NotImplementedError, "Method not implemented"
if n < 0
raise ArgumentError
elsif n == 0 || n == 1
return 1
else
return n * (factorial(n - 1))
end
end

# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n)
# Space complexity: O(n)
def reverse(s)

Choose a reason for hiding this comment

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

👍
This works, but because you create a new array with each recursive call this is O(n2) for both time/space complexity.

raise NotImplementedError, "Method not implemented"
if s.length <= 1
return s
else
return reverse(s[1..-1]) + s[0]

Choose a reason for hiding this comment

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

s[1..-1] creates a new array and copies all the individual elements over and so is O(n) by itself.

end
end

# Time complexity: ?
Expand All @@ -36,10 +46,18 @@ def search(array, value)
raise NotImplementedError, "Method not implemented"
end

# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n)
# Space complexity: O(n)
def is_palindrome(s)

Choose a reason for hiding this comment

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

👍 This works, but you have similar time/space issues with the above methods due to creating new arrays.

raise NotImplementedError, "Method not implemented"
if s.length == 1 || s.length == 0
return true
end

if s[0] != s[-1]
return false
end

return is_palindrome(s[1...-1])
end

# Time complexity: ?
Expand Down
4 changes: 2 additions & 2 deletions test/recursion_writing_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
end
end

xdescribe "reverse" do
describe "reverse" do
it "will reverse 'cat'" do
# Arrange
string = "cat"
Expand Down Expand Up @@ -260,7 +260,7 @@
end
end

xdescribe "is_palindrome" do
describe "is_palindrome" do
it "will return true for emptystring" do
# Arrange
string = ""
Expand Down