Code Logo

Reverse String

Published at24 Jul 2026
TypeScript String Handling Easy 0 views
Like0

Write a TypeScript function that reverses a given string. Build the reversed string character by character without using built-in reverse methods.

Loop through the original string from the last character to the first, appending each character to a result string. Use charAt() to access characters and return the accumulated result.

Edge cases include empty strings (return empty), single character strings (return unchanged), and strings with spaces.

String reversal is a classic programming exercise that teaches string manipulation and loop patterns. The backward iteration approach builds the result character by character, demonstrating how strings can be constructed in reverse order.

TypeScript's charAt() method safely accesses characters at specific positions. The string concatenation operator (+=) in JavaScript/TypeScript creates a new string with each operation, resulting in O(n) space usage for the result.

This manual approach avoids built-in methods like split(), reverse(), and join(), showing how these higher-level operations work internally.

Edge cases include empty strings (return empty), single characters, palindrome strings where the reversed string equals the original, and strings with spaces. The loop uses charAt() which returns an empty string for out-of-bounds indices.

Example Input & Output

Example 1
Input
"a"
Output
"a"
Example 2
Input
""
Output
""
Example 3
Input
"racecar"
Output
"racecar"
Example 4
Input
"Hello"
Output
"olleH"
Example 5
Input
"TypeScript"
Output
"tpircSepyT"

Algorithm Flow

Recommendation Algorithm Flow for Reverse String
Recommendation Algorithm Flow for Reverse String

Solution Approach

Initialize result = ''. Loop backwards from text.length - 1 down to 0. Use text.charAt(i) to get each character and append to result with +=.

The time complexity is O(n). Space complexity is O(n) for the result string.

Best Answers

typescript - Approach 1
function reverseString(text: string): string {
    var result = '';
    for (var i = text.length - 1; i >= 0; i--) {
        result += text.charAt(i);
    }
    return result;
}