CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
Reverse String Recursively
string
recursion
# Reverse String Recursively ## Difficulty Easy ## Tags `string`, `recursion` ## Problem Statement Write a recursive function to reverse a string. Do not use any loops. ## Constraints - 0 ≤ s.length ≤ 10⁴ - Use recursion only (no loops). ## Signatures ### Python ```python def reverse_recursive(s: str) -> str: pass ``` ### Java ```java public class Solution { public String reverse_recursive(String s) { return null; } } ``` ### Csharp ```csharp public class Solution { public string reverse_recursive(string s) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: string reverse_recursive(string s) { } }; ``` ### C ```c char* reverse_recursive(char* s) { } ``` ### Ruby ```ruby def reverse_recursive(s) end ``` ### Perl ```perl sub reverse_recursive { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def reverse_recursive(s: String): String = { } } ``` ### Haskell ```haskell reverse_recursive :: ... -> ... reverse_recursive args = undefined ``` ### Clojure ```clojure (defn reverse_recursive [s] ) ``` ### Scheme ```scheme (define (reverse_recursive s) ) ``` ## Examples ### Example 1 **Input:** ``` s = "hello" ``` **Output:** ``` "olleh" ``` ### Example 2 **Input:** ``` s = "a" ``` **Output:** ``` "a" ``` ### Example 3 **Input:** ``` s = "" ``` **Output:** ``` "" ``` ### Example 4 **Input:** ``` s = "ab" ``` **Output:** ``` "ba" ``` ## Hints 1. **Base case**: If string is empty or has one character, return it as-is. 2. **Recursive step**: Return `reverse(s[1:]) + s[0]` - Take the rest of the string, reverse it, append the first character. ### Example Trace for "hello" ``` reverse("hello") = reverse("ello") + "h" = (reverse("llo") + "e") + "h" = ((reverse("lo") + "l") + "e") + "h" = (((reverse("o") + "l") + "l") + "e") + "h" = ((("o" + "l") + "l") + "e") + "h" = "olleh" ```
Login required
Please log in to view the solution editor and submit code.
Login
Register