Bird
Raised Fist0
DSA Javascriptprogramming

String Reversal Approaches in DSA Javascript

Choose your learning style10 modes available
Mental Model
Reversing a string means making the last letter come first and the first letter come last, flipping the order of all letters.
Analogy: Imagine reading a sentence backwards, starting from the end and moving to the beginning, like rewinding a tape to hear the words in reverse order.
Original: h -> e -> l -> l -> o -> null
Reversed: o -> l -> l -> e -> h -> null
Dry Run Walkthrough
Input: string: "hello"
Goal: Reverse the string so it becomes "olleh"
Step 1: Start with empty result string and pointer at last character 'o'
result: "o"
Why: We add the last character first to build the reversed string
Step 2: Add second last character 'l' to result
result: "ol"
Why: Continue adding characters from end to start
Step 3: Add next character 'l' to result
result: "oll"
Why: Keep building reversed string by adding characters in reverse order
Step 4: Add next character 'e' to result
result: "olle"
Why: Add next character from original string moving backward
Step 5: Add first character 'h' to result
result: "olleh"
Why: Finish by adding the first character last
Result:
olleh
Annotated Code
DSA Javascript
class StringReversal {
  // Reverse string by building new string from end to start
  static reverseByAppending(str) {
    let reversed = "";
    for (let i = str.length - 1; i >= 0; i--) {
      reversed += str[i]; // add character from end
    }
    return reversed;
  }

  // Reverse string by swapping characters in array in place
  static reverseInPlace(str) {
    let arr = str.split(""); // convert to array
    let left = 0;
    let right = arr.length - 1;
    while (left < right) {
      // swap characters
      [arr[left], arr[right]] = [arr[right], arr[left]];
      left++; // move left pointer right
      right--; // move right pointer left
    }
    return arr.join(""); // convert back to string
  }
}

// Driver code
const input = "hello";
console.log(StringReversal.reverseByAppending(input));
console.log(StringReversal.reverseInPlace(input));
for (let i = str.length - 1; i >= 0; i--) {
iterate from last character to first to build reversed string
reversed += str[i]; // add character from end
append current character to result string
let arr = str.split("");
convert string to array for in-place swapping
while (left < right) {
loop until pointers meet in middle
[arr[left], arr[right]] = [arr[right], arr[left]];
swap characters at left and right pointers
left++; right--;
move pointers inward to continue swapping
OutputSuccess
olleh olleh
Complexity Analysis
Time: O(n) because we process each character once either by appending or swapping
Space: O(n) for reverseByAppending due to new string creation; O(n) for reverseInPlace due to array conversion
vs Alternative: Appending creates a new string which uses extra space; in-place swapping uses array but modifies characters without building a new string step by step
Edge Cases
empty string ""
returns empty string without error
DSA Javascript
for (let i = str.length - 1; i >= 0; i--) {
single character string "a"
returns the same single character string
DSA Javascript
while (left < right) {
string with spaces "a b"
reverses all characters including spaces correctly
DSA Javascript
reversed += str[i]; // add character from end
When to Use This Pattern
When you need to reverse the order of characters in a string, use string reversal approaches like building a new reversed string or swapping characters in place.
Common Mistakes
Mistake: Trying to modify string characters directly since strings are immutable
Fix: Convert string to array before swapping characters
Mistake: Appending characters in forward order instead of backward
Fix: Iterate from the last character to the first
Summary
Reverses a string by either building a new reversed string or swapping characters in place.
Use when you need the characters in a string in reverse order.
The key insight is that strings are immutable, so reversing often requires building a new string or using an array for swapping.

Practice

(1/5)
1. What does the JavaScript method split('') do when applied to a string?
easy
A. It reverses the string characters.
B. It removes all spaces from the string.
C. It joins array elements into a string.
D. It converts the string into an array of individual characters.

Solution

  1. Step 1: Understand the split method

    The split('') method splits a string into an array by each character because the separator is an empty string.
  2. Step 2: Effect on string

    For example, 'hello'.split('') becomes ['h', 'e', 'l', 'l', 'o'].
  3. Final Answer:

    It converts the string into an array of individual characters. -> Option D
  4. Quick Check:

    split('') = array of chars [OK]
Hint: split('') breaks string into chars array [OK]
Common Mistakes:
  • Thinking split('') reverses the string
  • Confusing split('') with join()
  • Assuming split('') removes spaces
2. Which of the following is the correct syntax to reverse a string str in JavaScript using built-in methods?
easy
A. str.reverse().join('')
B. str.split('').reverse().join('')
C. reverse(str).split('').join('')
D. str.join('').reverse()

Solution

  1. Step 1: Understand string and array methods

    Strings do not have a reverse() method, but arrays do. So first convert string to array using split('').
  2. Step 2: Reverse array and join back

    Use reverse() on the array, then join('') to convert back to string.
  3. Final Answer:

    str.split('').reverse().join('') -> Option B
  4. Quick Check:

    split + reverse + join = reversed string [OK]
Hint: Split string, reverse array, join back [OK]
Common Mistakes:
  • Trying to call reverse() directly on string
  • Using join() before reverse()
  • Using incorrect method order
3. What is the output of the following code?
const str = 'abc';
const reversed = str.split('').reverse().join('');
console.log(reversed);
medium
A. Error: reverse is not a function
B. 'abc'
C. 'cba'
D. ['c', 'b', 'a']

Solution

  1. Step 1: Split string into array

    'abc'.split('') becomes ['a', 'b', 'c'].
  2. Step 2: Reverse array and join

    ['a', 'b', 'c'].reverse() becomes ['c', 'b', 'a'], then .join('') makes it 'cba'.
  3. Final Answer:

    'cba' -> Option C
  4. Quick Check:

    split + reverse + join = 'cba' [OK]
Hint: Split, reverse, join outputs reversed string [OK]
Common Mistakes:
  • Expecting original string output
  • Expecting array output instead of string
  • Confusing method order causing errors
4. Identify the error in this string reversal code:
function reverseString(s) {
  return s.reverse().join('');
}
medium
A. Strings do not have reverse() method.
B. join() cannot be used on strings.
C. Function missing return statement.
D. split('') is missing before reverse().

Solution

  1. Step 1: Check string methods

    Strings do not have reverse(), so calling s.reverse() causes error.
  2. Step 2: Fix by splitting string

    We must convert string to array first using s.split('') before reversing.
  3. Final Answer:

    Strings do not have reverse() method. -> Option A
  4. Quick Check:

    No reverse() method on strings [OK]
Hint: Strings do not have reverse() method [OK]
Common Mistakes:
  • Trying to reverse string directly
  • Ignoring need to split string
  • Misunderstanding join() usage
5. Given the function below, what will reverseString('hello world') return?
function reverseString(s) {
  let reversed = '';
  for (let i = s.length - 1; i >= 0; i--) {
    reversed += s[i];
  }
  return reversed;
}
hard
A. 'dlrow olleh'
B. 'hello world'
C. 'helloworld'
D. Error: Cannot read property 'length' of undefined

Solution

  1. Step 1: Loop from end to start

    The for loop starts at last character index and moves backward to 0, appending each character to reversed.
  2. Step 2: Build reversed string

    Characters are added in reverse order, so 'hello world' becomes 'dlrow olleh'.
  3. Final Answer:

    'dlrow olleh' -> Option A
  4. Quick Check:

    Loop backward appends chars reversed [OK]
Hint: Loop backward to build reversed string [OK]
Common Mistakes:
  • Looping forward instead of backward
  • Not appending characters correctly
  • Confusing string concatenation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard