ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Scala String Reversal using Recursion

Scala

Goal -- WPM

Ready
Exercise Algorithm Area
1object StringReverser {
2
3/**
4* Reverses a given string using a simple recursive approach.
5* This method breaks down the problem by taking the first character,
6* recursively reversing the rest of the string, and then appending
7* the first character to the end of the reversed substring.
8*
9* @param str The string to be reversed.
10* @return The reversed string.
11*/
12def reverseString(str: String): String = {
13// Base case 1: If the string is null or empty, return an empty string.
14if (str == null || str.isEmpty) {
15""
16}
17// Base case 2: If the string has only one character, it's already reversed.
18else if (str.length == 1) {
19str
20}
21// Recursive step: Reverse the rest of the string and append the first character.
22else {
23reverseString(str.substring(1)) + str.charAt(0)
24}
25}
26
27/**
28* Main method to demonstrate the string reversal functionality.
29* It tests the `reverseString` method with various inputs, including
30* an empty string, a single-character string, a typical string, and a string with spaces.
31*/
32def main(args: Array[String]): Unit = {
33val testString1 = "Hello, Scala!"
34val reversedString1 = reverseString(testString1)
35println(s"Original: '$testString1', Reversed: '$reversedString1'") // Expected: '!aclaS ,olleH'
36
37val testString2 = ""
38val reversedString2 = reverseString(testString2)
39println(s"Original: '$testString2', Reversed: '$reversedString2'") // Expected: ''
40
41val testString3 = "a"
42val reversedString3 = reverseString(testString3)
43println(s"Original: '$testString3', Reversed: '$reversedString3'") // Expected: 'a'
44
45val testString4 = "madam"
46val reversedString4 = reverseString(testString4)
47println(s"Original: '$testString4', Reversed: '$reversedString4'") // Expected: 'madam'
48
49val testString5 = " leading and trailing spaces "
50val reversedString5 = reverseString(testString5)
51println(s"Original: '$testString5', Reversed: '$reversedString5'") // Expected: ' secaps gniliart dna gnidael '
52}
53}
Algorithm description viewbox

Scala String Reversal using Recursion

Algorithm description:

This Scala program reverses a string using a straightforward recursive function. The function operates by taking the first character of the string, recursively reversing the remainder of the string, and then concatenating the first character to the end of the reversed substring. This approach elegantly breaks down the problem into smaller, self-similar subproblems until a base case is reached.

Algorithm explanation:

The `reverseString` function handles three cases: null or empty strings, single-character strings, and strings with multiple characters. For null or empty strings, it returns an empty string. For a single-character string, it returns the string itself as it's already reversed. For longer strings, it recursively calls `reverseString` on the substring starting from the second character (`str.substring(1)`) and then appends the first character (`str.charAt(0)`) to the result. This process continues until the base case of an empty string is reached. The time complexity is O(n^2) due to string concatenation in each recursive call, where n is the length of the string. A more efficient O(n) solution would use a mutable `StringBuilder` or an iterative approach. The space complexity is O(n) due to the recursion depth, which can lead to stack overflow for very long strings. Edge cases handled include null input, empty strings, and single-character strings.

Pseudocode:

function reverse_string(str):
  if str is null or empty:
    return ""
  else if length(str) == 1:
    return str
  else:
    return reverse_string(substring(str, 1, end)) + first_character(str)