Q1: Reverse a String Without Built-In Reverse

To reverse a string manually, iterate backward from the last character to the first, appending each character to a new string. This demonstrates basic iteration and string accumulation.

Manual String Reversal
function reverseString(str) {
  let reversed = '';
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

console.log(reverseString('hello')); // 'olleh'
💡 By looping from str.length - 1 down to 0, each character is appended in reverse order without using Array.prototype.reverse().
Key Takeaways
  • Iterates backward from the end of the string to assemble a new reversed string.
  • Runs with O(n) time complexity and O(n) space complexity.
Knowledge Check

What is the time complexity of reversing a string of length n character-by-character?