Basic Questions
Sum of Natural Numbers
Code
Explanation
- Base case:
n == 1
- Recursive case:
n + sum(n - 1)
Analysis
- Time Complexity:
O(n)
- Space Complexity:
O(n)
Decimal to Binary COnversion
Code
Explanation
- Base case:
n == 0
- Recursive case:
decimalToBinnary(num / 2)
- Print the remainder of
num / 2
Analysis
- Time Complexity:
O(log n)
- Space Complexity:
O(log n)
Modulo Operation
Code
Explanation
- Base case:
num < den
- Recursive case:
mod(num - den, den)
- Return
num
whennum < den
Analysis
- Time Complexity:
O(n)
- Space Complexity:
O(n)
Find String Length
Code
Explanation
- Base case:
str[0] == '\0'
- Recursive case:
stringLength(str.substr(1))
- Return
1
whenstr[0] == '\0'
Analysis
- Time Complexity:
O(n)
- Space Complexity:
O(n)
Reverse a String
Code
Explanation
- Base case:
str[0] == '\0'
- Recursive case:
reverse(str.substr(1))
- Print
str[0]
whenstr[0] == '\0'
Analysis
- Time Complexity:
O(n)
- Space Complexity:
O(n)
Check if string is Palindrome
Code
Explanation
- Base case:
start >= end
- Recursive case:
isPalindrome(str, start + 1, end - 1)
- Return
true
whenstart >= end
- Return
false
whenstr[start] != str[end]
Analysis
- Time Complexity:
O(n)
- Space Complexity:
O(n)
Count Vowels in a String
Code
Explanation
- Base case:
start >= end
- Recursive case:
countVowels(str, start + 1, end)
- Return
0
whenstart >= end
- Return
count + 1
whenstr[start]
is a vowel
Analysis
- Time Complexity:
O(n)
- Space Complexity:
O(n)
Sum of numbers in a Singly Linked List
Code
Note: Once you have understood the above examples, try to solve the following problems on your own. (
Using Recursion
)
Extra Problems
- Print numbers from 1 to n
- Print numbers from n to 1