Bird
Raised Fist0
DSA Typescriptprogramming

String Reversal Approaches in DSA Typescript

Choose your learning style10 modes available
Mental Model
Reversing a string means flipping its characters so the last becomes first and the first becomes last.
Analogy: Imagine reading a sentence backwards, starting from the end and moving to the beginning, like rewinding a tape.
s t r i n g
↑           
(front)      
Dry Run Walkthrough
Input: string: "code"
Goal: Reverse the string so it reads "edoc"
Step 1: start with two pointers: left at 'c' (index 0), right at 'e' (index 3)
c [left] o d e [right]
indexes: 0       3
Why: We need to swap characters from both ends moving towards the center
Step 2: swap characters at left and right: 'c' and 'e'
e [left] o d c [right]
indexes: 0       3
Why: Swapping first and last characters starts reversing the string
Step 3: move left pointer to index 1 ('o'), right pointer to index 2 ('d')
e o [left] d [right] c
indexes: 1       2
Why: Move pointers inward to continue swapping next pair
Step 4: swap characters at left and right: 'o' and 'd'
e d [left] o [right] c
indexes: 1       2
Why: Swapping these characters continues the reversal
Step 5: move pointers inward: left to index 2, right to index 1; pointers crossed, stop
e d o c
indexes crossed
Why: Pointers crossed means all swaps done, string reversed
Result:
e d o c
Reversed string: "edoc"
Annotated Code
DSA Typescript
class StringReversal {
  static reverseInPlace(str: string): string {
    const arr = str.split('');
    let left = 0;
    let right = arr.length - 1;
    while (left < right) {
      // swap characters at left and right
      const temp = arr[left];
      arr[left] = arr[right];
      arr[right] = temp;
      // move pointers inward
      left++;
      right--;
    }
    return arr.join('');
  }

  static reverseUsingBuiltIn(str: string): string {
    return str.split('').reverse().join('');
  }
}

// Driver code
const input = "code";
console.log("Reverse in place:", StringReversal.reverseInPlace(input));
console.log("Reverse using built-in:", StringReversal.reverseUsingBuiltIn(input));
while (left < right) {
loop until pointers cross to swap characters from ends inward
const temp = arr[left]; arr[left] = arr[right]; arr[right] = temp;
swap characters at left and right pointers
left++; right--;
move pointers inward to next pair
return arr.join('');
join array back to string after reversal
return str.split('').reverse().join('');
alternative approach using built-in reverse method
OutputSuccess
Reverse in place: edoc Reverse using built-in: edoc
Complexity Analysis
Time: O(n) because we swap characters from both ends moving towards the center, touching each character once
Space: O(n) because we convert the string to an array of characters to swap in place
vs Alternative: The built-in reverse method also uses O(n) time and space internally but is simpler to write; manual swapping shows the underlying process
Edge Cases
empty string ""
returns empty string immediately without swaps
DSA Typescript
while (left < right) {
single character string "a"
returns the same single character string as reversal is itself
DSA Typescript
while (left < right) {
string with repeated characters "aaa"
reverses correctly to "aaa" which looks the same
DSA Typescript
while (left < right) {
When to Use This Pattern
When you need to reverse or flip a sequence of characters, reach for the two-pointer swap pattern because it efficiently reverses in place.
Common Mistakes
Mistake: Swapping characters without moving pointers inward, causing infinite loop
Fix: Increment left and decrement right pointers after each swap
Mistake: Trying to reverse string directly without converting to array (strings are immutable)
Fix: Convert string to array first, then swap characters
Summary
Reverses a string by swapping characters from both ends moving inward.
Use when you need to reverse strings efficiently without extra complex operations.
The key insight is using two pointers to swap characters until they meet or cross.

Practice

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

Solution

  1. Step 1: Understand the split method

    The split('') method breaks a string into an array of characters by splitting at every empty string between characters.
  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 B
  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 using built-in methods in TypeScript?
easy
A. str.split('').reverse().join('')
B. str.reverse().join('')
C. reverse(str).split('')
D. str.join('').reverse()

Solution

  1. Step 1: Split string into array

    Use str.split('') to convert string into array of characters.
  2. Step 2: Reverse and join

    Use reverse() on array, then join('') to form reversed string.
  3. Final Answer:

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

    split + reverse + join = reversed string [OK]
Hint: Split, reverse array, then join to reverse string [OK]
Common Mistakes:
  • Calling reverse() directly on string
  • Using join() before reverse()
  • Using reverse() as a standalone function
3. What will be the output of the following TypeScript code?
const str = "abcde";
const reversed = str.split('').reverse().join('');
console.log(reversed);
medium
A. "edcbe"
B. "abcde"
C. ""
D. "edcba"

Solution

  1. Step 1: Split string into array

    "abcde".split('') becomes ["a", "b", "c", "d", "e"].
  2. Step 2: Reverse and join array

    Reversing gives ["e", "d", "c", "b", "a"], joining results in "edcba".
  3. Final Answer:

    "edcba" -> Option D
  4. Quick Check:

    split + reverse + join = "edcba" [OK]
Hint: Split, reverse, join outputs reversed string [OK]
Common Mistakes:
  • Expecting original string output
  • Mixing up reversed characters
  • Forgetting to join after reverse
4. Identify the error in this TypeScript function intended to reverse a string:
function reverseString(s: string): string {
  return s.reverse();
}
medium
A. Strings do not have a reverse() method directly.
B. The function should return void, not string.
C. The parameter should be an array, not a string.
D. The function is missing a return statement.

Solution

  1. Step 1: Check string methods

    Strings in TypeScript do not have a reverse() method directly; only arrays do.
  2. Step 2: Correct approach

    Convert string to array with split(''), reverse array, then join back.
  3. Final Answer:

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

    reverse() works on arrays, not strings [OK]
Hint: reverse() is for arrays, not strings [OK]
Common Mistakes:
  • Trying to call reverse() on string directly
  • Ignoring need to split string first
  • Assuming reverse() returns void
5. Given the function below, what will be the output when calling reverseString('12345')?
function reverseString(s: string): string {
  let reversed = '';
  for (let i = s.length - 1; i >= 0; i--) {
    reversed += s[i];
  }
  return reversed;
}
hard
A. "5432"
B. "12345"
C. "54321"
D. ""

Solution

  1. Step 1: Loop from end to start

    The loop starts at index 4 (last char '5') and moves backward to 0.
  2. Step 2: Build reversed string

    Characters are appended in reverse order: '5', '4', '3', '2', '1'.
  3. Final Answer:

    "54321" -> Option C
  4. Quick Check:

    Loop backward concatenates reversed string [OK]
Hint: Loop backward to build reversed string [OK]
Common Mistakes:
  • Looping forward instead of backward
  • Off-by-one errors in loop index
  • Not initializing reversed string properly
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