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

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

Basic String Reversal

TSX

Goal -- WPM

Ready
Exercise Algorithm Area
1function reverseString(str: string): string {
2let reversed = '';
3for (let i = str.length - 1; i >= 0; i--) {
4reversed += str[i];
5}
6return reversed;
7}
Algorithm description viewbox

Basic String Reversal

Algorithm description:

This function reverses a given string. It's a common introductory programming problem used to practice string manipulation and loop control. It can be applied in scenarios like reversing user input for display or in simple text processing tasks.

Algorithm explanation:

The `reverseString` function iterates through the input string from the last character to the first. It initializes an empty string `reversed`. In each iteration, it appends the current character to the `reversed` string. This builds the reversed string character by character. The loop condition `i >= 0` ensures all characters are processed. The time complexity is O(n), where n is the length of the string, because each character is accessed and appended once. The space complexity is O(n) because a new string of the same length is created to store the reversed result.

Pseudocode:

function reverseString(inputString):
  initialize reversedString to empty
  loop from last character index down to 0:
    append current character to reversedString
  return reversedString