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

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

Octave String Reversal with Helper

Octave

Goal -- WPM

Ready
Exercise Algorithm Area
1function reversedStr = reverseStringWithHelper(inputStr)
2% Reverses a given string using a helper function.
3% Handles empty and single-character strings as edge cases.
4
5n = length(inputStr);
6
7% Edge case: empty string
8if n == 0
9reversedStr = "";
10return;
11end
12
13% Edge case: single character string
14if n == 1
15reversedStr = inputStr;
16return;
17end
18
19% Initialize the reversed string with the same length
20reversedStr = repmat(' ', 1, n);
21
22% Call the helper function to perform the reversal
23reversedStr = doReverse(inputStr, reversedStr, n);
24end
25
26function reversed = doReverse(original, target, len)
27% Helper function to perform the actual character swapping.
28% Iterates from the beginning of the original string and places
29% characters in reverse order into the target string.
30
31for i = 1:len
32% The character at index i in original goes to index (len - i + 1) in target
33target(len - i + 1) = original(i);
34end
35reversed = target;
36end
Algorithm description viewbox

Octave String Reversal with Helper

Algorithm description:

This Octave function reverses a given input string. It utilizes a helper function to manage the core reversal logic. This approach is useful in scenarios where string manipulation is a frequent operation, such as data preprocessing or text-based game development.

Algorithm explanation:

The `reverseStringWithHelper` function takes an input string and returns its reversed version. It first checks for edge cases: an empty string and a single-character string, returning them directly. For longer strings, it initializes an output string of the same length and then calls the `doReverse` helper function. The `doReverse` helper iterates through the original string from the first character to the last. In each iteration, it places the current character from the original string into the corresponding reversed position in the target string. The time complexity is O(n), where n is the length of the string, because each character is accessed and copied once. The space complexity is O(n) due to the creation of the new reversed string. The invariant maintained is that after iteration `i`, the first `i` characters of the original string have been correctly placed in the last `i` positions of the reversed string.

Pseudocode:

function reverseStringWithHelper(inputStr):
  n = length(inputStr)
  if n is 0:
    return ""
  if n is 1:
    return inputStr
  reversedStr = create empty string of length n
  reversedStr = doReverse(inputStr, reversedStr, n)
  return reversedStr

function doReverse(original, target, len):
  for i from 1 to len:
    target[len - i + 1] = original[i]
  return target