Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the sum of all elements in the array using recursion.
DSA C#
int SumArray(int[] arr, int index) {
if (index == arr.Length) {
return 0;
}
return arr[index] + [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the same index in the recursive call causes infinite recursion.
Decreasing the index leads to invalid array access.
✗ Incorrect
The function calls itself with the next index to sum all elements recursively.
2fill in blank
mediumComplete the code to check if a string is a palindrome using recursion.
DSA C#
bool IsPalindrome(string s, int start, int end) {
if (start >= end) {
return true;
}
if (s[start] != s[end]) {
return false;
}
return [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Only moving one pointer causes incorrect checks.
Not moving pointers leads to infinite recursion.
✗ Incorrect
The function moves inward by increasing start and decreasing end to check characters recursively.
3fill in blank
hardFix the error in the recursive function that counts occurrences of a character in a string.
DSA C#
int CountChar(string s, char c, int index) {
if (index == s.Length) {
return 0;
}
int count = (s[index] == c) ? 1 : 0;
return count + [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Decreasing the index causes invalid access and infinite recursion.
Using the same index causes infinite recursion.
✗ Incorrect
The function should move forward by increasing the index to count all occurrences correctly.
4fill in blank
hardFill both blanks to create a recursive function that reverses a string.
DSA C#
string ReverseString(string s, int start, int end) {
if (start >= end) {
return s;
}
char temp = s[start];
s = s.Remove(start, 1).Insert(start, s[end].ToString());
s = s.Remove(end, 1).Insert(end, temp.ToString());
return ReverseString(s, [1], [2]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Moving pointers in the wrong direction causes infinite recursion.
Not updating pointers causes the same characters to be swapped repeatedly.
✗ Incorrect
The function moves inward by increasing start and decreasing end to swap characters recursively.
5fill in blank
hardFill all three blanks to create a recursive function that builds a dictionary of word lengths for words longer than 3 characters.
DSA C#
Dictionary<string, int> WordLengths(List<string> words) {
if (words.Count == 0) {
return new Dictionary<string, int>();
}
var result = WordLengths(words.GetRange(1, words.Count - 1));
string word = words[0];
if (word.Length > 3) {
result[[1]] = [2];
}
return result;
}
// Usage: var lengths = WordLengths(new List<string> {"apple", "bat", "carrot"});Attempts:
3 left
💡 Hint
Common Mistakes
Using the list name instead of the current word as the key.
Using the count of words instead of the length of the word.
✗ Incorrect
The dictionary key is the current word, and the value is its length. The word is accessed as 'word'.
