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
57 changes: 49 additions & 8 deletions lib/recursive-methods.rb
Original file line number Diff line number Diff line change
@@ -1,33 +1,74 @@
# 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"
return 1 if n == 1

if n < 0
raise ArgumentError.new("n must be >=0")
end

return n * factorial(n-1)
end

# Time complexity: ?
# Space complexity: ?
def reverse(s)
raise NotImplementedError, "Method not implemented"

end

# Time complexity: ?
# Space complexity: ?
def reverse_inplace(s)
raise NotImplementedError, "Method not implemented"
return reverse_inplace_recursive(s, 0)
end

def reverse_inplace_recursive(s, index)

if s.length / 2 == index
return s
end

temp_char = s[index]
s[index] = s[s.length - 1 - index]
s[s.length - 1 - index] = temp_char

# alternative way for the same thing
# temp_char = s[s.length - 1 - index]
# s[s.length - 1 - index] = s[index]
# s[index] = temp_char

return reverse_inplace_recursive(s, index + 1)
end

# Time complexity: ?
# Space complexity: ?
def bunny(n)
raise NotImplementedError, "Method not implemented"
if n == 0
return n
end

return 2 + bunny(n - 1)
end

# Time complexity: ?
# Space complexity: ?
def nested(s)
raise NotImplementedError, "Method not implemented"
def nested(s, index = 0)
if s.length % 2 == 1
return false
end

if s.length / 2 == index
return true
end

if s[index] == s[s.length - 1 - index]
return false
end

return nested(s, index + 1)

end

# Time complexity: ?
Expand Down
2 changes: 1 addition & 1 deletion test/recursion_writing_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@
end
end

xdescribe "nested" do
describe "nested" do
it "will return true for empystring" do
# Arrange
string = ""
Expand Down