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

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

Simple String Reversal

TypeScript

Goal -- WPM

Ready
Exercise Algorithm Area
1function reverseString(str: string): string {
2// Handle empty string edge case
3if (str === "") {
4return "";
5}
6
7let reversedStr = "";
8// Iterate from the last character to the first
9for (let i = str.length - 1; i >= 0; i--) {
10// Append the current character to the reversed string
11reversedStr += str[i];
12}
13
14// Return the fully reversed string
15return reversedStr;
16}
17
18// Example Usage:
19// const original = "hello world!";
20// const reversed = reverseString(original);
21// console.log(reversed); // Output: "!dlrow olleh"
22
23// const emptyStr = "";
24// console.log(reverseString(emptyStr)); // Output: ""
25
26// const specialChars = "@#$%^&*()";
27// console.log(reverseString(specialChars)); // Output: ")(*&^%$#@"
Algorithm description viewbox

Simple String Reversal

Algorithm description:

This function reverses a given string. It iterates through the input string from the last character to the first, appending each character to a new string. This is a fundamental string manipulation task with applications in text processing, data validation, and educational programming exercises.

Algorithm explanation:

The `reverseString` function takes a string as input and returns its reversed version. It initializes an empty string `reversedStr`. A `for` loop iterates from the last index of the input string (`str.length - 1`) down to `0`. In each iteration, the character at the current index `i` is appended to `reversedStr`. This builds the reversed string character by character. The function includes an edge case check for an empty input string, returning an empty string immediately to avoid unnecessary processing. The time complexity is O(N), where N is the length of the string, because each character is processed exactly once. The space complexity is also O(N) because a new string of length N is created to store the result. This approach correctly handles all characters, including Unicode characters and special symbols, as string indexing and concatenation work consistently across them.

Pseudocode:

Function reverseString(str):
  If str is empty:
    Return ""

  reversedStr = ""
  Loop from i = length of str - 1 down to 0:
    Append character at index i of str to reversedStr

  Return reversedStr