Skip to content
Open
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
50 changes: 38 additions & 12 deletions lib/recursive-methods.rb
Original file line number Diff line number Diff line change
@@ -1,27 +1,53 @@
# 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)
raise NotImplementedError, "Method not implemented"
if n == 0
return 1
else
return n * (factorial(n - 1))
end
end

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

Choose a reason for hiding this comment

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

Time complexity is also O(n^2) since you have n recursive calls and each call creates a new array with s[1..-1]

# Space complexity: O(n^2)
def reverse(s)
raise NotImplementedError, "Method not implemented"
if s.length <= 1
return s
end
reversed_s = reverse(s[1..-1])
reversed_s += s[0]
reversed_s
end

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

Choose a reason for hiding this comment

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

👍

# Space complexity: O(n)
def reverse_inplace(s)
raise NotImplementedError, "Method not implemented"
i = 0
k = s.length - 1

return helper(s, i, j)
end

def helper(s, i, k)
if k <= i
return s
end

temp = s[i]
s[i] = s[k]
s[k] = temp
return helper(s, i + 1, k - 1)
end

# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n)
# Space complexity: O(n)
def bunny(n)
raise NotImplementedError, "Method not implemented"
if n == 0
return 0
else return 2 + bunny(n-1)

Choose a reason for hiding this comment

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

Cleaning up this indentation would be better.

end
end

# Time complexity: ?
Expand Down