Bird
Raised Fist0
DSA C#programming~10 mins

String Reversal Approaches in DSA C# - Execution Trace

Choose your learning style10 modes available
Concept Flow - String Reversal Approaches
Start with original string
↓
Choose reversal method
↓
Using loop
↓
Build reversed string step by step
↓
Return reversed string
The flow shows starting with the original string, choosing a reversal method, building the reversed string, and returning it.
Execution Sample
DSA C#
string ReverseUsingLoop(string s) {
  char[] arr = s.ToCharArray();
  int left = 0, right = arr.Length - 1;
  while (left < right) {
    var temp = arr[left]; arr[left++] = arr[right]; arr[right--] = temp;
  }
  return new string(arr);
}
This code reverses a string by swapping characters from both ends moving towards the center.
Execution Table
StepOperationleftrightCharacters SwappedString State
1Initialize pointers04Nonehello
2Swap arr[0] and arr[4]13'h' <-> 'o'oellh
3Swap arr[1] and arr[3]22'e' <-> 'l'olleh
4Check condition left < right (2 < 2)22No swapolleh
5Return reversed string---olleh
💡 Loop ends when left is not less than right (left=2, right=2)
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
left01222
right43222
arr['h','e','l','l','o']['o','e','l','l','h']['o','l','l','e','h']['o','l','l','e','h']['o','l','l','e','h']
Key Moments - 3 Insights
Why do we stop swapping when left equals right?
Because when left equals right, the middle character (in odd length strings) is already in place, so no swap is needed. See execution_table step 4 where left=2 and right=2, loop ends.
Why do we swap characters instead of creating a new string directly?
Strings are immutable in C#, so we convert to a char array to swap characters in place efficiently. This is shown in execution_table steps 2 and 3 where characters are swapped in the array.
What happens if the input string is empty?
The loop condition left < right will be false immediately, so no swaps occur and the empty string is returned as is.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the string state after step 3?
Ahello
Boellh
Colleh
Dolle
💡 Hint
Check the 'String State' column in execution_table row for step 3.
At which step does the loop condition become false?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the 'Operation' and 'left' and 'right' values in execution_table step 4.
If the input string was 'abcd', what would be the string state after the first swap?
Adcba
Bdbca
Cbcda
Dabcd
💡 Hint
Think about swapping first and last characters only, like in execution_table step 2.
Concept Snapshot
String Reversal Approaches in C#:
- Convert string to char array for mutability
- Use two pointers (left, right) to swap characters
- Move pointers inward until they meet or cross
- Return new string from modified char array
- Handles empty and odd-length strings correctly
Full Transcript
This visual execution traces reversing a string using a two-pointer approach in C#. We start with the original string 'hello'. We convert it to a char array to allow swapping characters. Two pointers, left at 0 and right at 4, mark the start and end. We swap characters at these pointers: 'h' and 'o', resulting in 'oellh'. Then we move pointers inward: left=1, right=3. Swap 'e' and 'l' to get 'olleh'. When left equals right at 2, the loop ends because the middle character is in place. The reversed string 'olleh' is returned. This method efficiently reverses strings by swapping in place on a char array.

Practice

(1/5)
1. What does the string.Reverse() method in C# do when applied to a string?
easy
A. Returns a sequence of characters in reverse order
B. Modifies the original string to be reversed
C. Throws an error because strings are immutable
D. Converts the string to uppercase

Solution

  1. Step 1: Understand string.Reverse() behavior

    The Reverse() method returns an IEnumerable<char> with characters in reverse order but does not change the original string.
  2. Step 2: Check string immutability

    Strings in C# are immutable, so Reverse() cannot modify the original string directly.
  3. Final Answer:

    Returns a sequence of characters in reverse order -> Option A
  4. Quick Check:

    string.Reverse() returns reversed sequence [OK]
Hint: Reverse() returns reversed chars sequence, original string unchanged [OK]
Common Mistakes:
  • Thinking Reverse() changes the original string
  • Expecting Reverse() to return a string directly
  • Confusing Reverse() with ToUpper()
2. Which of the following is the correct syntax to reverse a string str and convert it back to a string in C#?
easy
A. string reversed = new string(str.Reverse().ToArray());
B. string reversed = str.Reverse().ToString();
C. string reversed = string.Reverse(str);
D. string reversed = str.Reverse().Join("");

Solution

  1. Step 1: Use Reverse() and convert to string

    str.Reverse() returns IEnumerable<char>, so to get a string, wrap it with new string(...) after converting to array.
  2. Step 2: Check each option

    string reversed = new string(str.Reverse().ToArray()); correctly uses new string(str.Reverse().ToArray()). string reversed = str.Reverse().ToString(); calls ToString() on IEnumerable<char>, which returns type name, not reversed string. string reversed = string.Reverse(str); is invalid syntax. string reversed = str.Reverse().Join(""); uses Join incorrectly (should be string.Join).
  3. Final Answer:

    string reversed = new string(str.Reverse().ToArray()); -> Option A
  4. Quick Check:

    Use new string(str.Reverse().ToArray()) to reverse string [OK]
Hint: Wrap Reverse() with new string() and ToArray() to get reversed string [OK]
Common Mistakes:
  • Calling ToString() on Reverse() result
  • Using string.Reverse() as static method
  • Incorrect use of Join method
3. What will be the output of the following C# code?
string input = "hello";
char[] arr = input.ToCharArray();
Array.Reverse(arr);
string reversed = new string(arr);
Console.WriteLine(reversed);
medium
A. olleh\n
B. hello
C. olleh
D. Error at Array.Reverse

Solution

  1. Step 1: Convert string to char array

    input.ToCharArray() creates ['h','e','l','l','o'].
  2. Step 2: Reverse the char array

    Array.Reverse(arr) reverses array to ['o','l','l','e','h'].
  3. Step 3: Create new string from reversed array

    new string(arr) creates "olleh" string.
  4. Step 4: Print reversed string

    Console.WriteLine prints "olleh" without extra characters.
  5. Final Answer:

    olleh -> Option C
  6. Quick Check:

    Char array reversed then joined = olleh [OK]
Hint: Reverse char array then new string gives reversed string [OK]
Common Mistakes:
  • Expecting Array.Reverse to return a value
  • Printing char array directly instead of string
  • Confusing reversed string with original
4. Identify the error in the following code that attempts to reverse a string:
string s = "world";
string reversed = s.Reverse().ToString();
Console.WriteLine(reversed);
medium
A. s is immutable, so Reverse() cannot be called
B. Console.WriteLine cannot print reversed string
C. Missing semicolon after Reverse()
D. Reverse() returns IEnumerable<char>, ToString() does not convert to string

Solution

  1. Step 1: Understand Reverse() return type

    s.Reverse() returns IEnumerable<char>, not a string.
  2. Step 2: ToString() on IEnumerable<char>

    Calling ToString() on IEnumerable<char> returns type name, not reversed string.
  3. Step 3: Correct way to convert reversed chars to string

    Use new string(s.Reverse().ToArray()) to get reversed string.
  4. Final Answer:

    Reverse() returns IEnumerable<char>, ToString() does not convert to string -> Option D
  5. Quick Check:

    ToString() on IEnumerable<char> ≠ reversed string [OK]
Hint: ToString() on Reverse() result returns type name, not string [OK]
Common Mistakes:
  • Assuming ToString() converts reversed chars to string
  • Ignoring need to convert IEnumerable<char> to array
  • Thinking Reverse() modifies original string
5. You want to reverse only the vowels in a string "education" while keeping other characters in place. Which approach is best in C#?
hard
A. Use Regex to remove vowels, reverse string, then append vowels at end
B. Convert string to char array, swap vowels using two pointers, then create new string
C. Use string.Reverse() to reverse entire string and then replace consonants
D. Call ToCharArray(), reverse array, then convert back to string

Solution

  1. Step 1: Understand problem requirement

    Only vowels should be reversed, consonants stay in place.
  2. Step 2: Evaluate approaches

    Convert string to char array, swap vowels using two pointers, then create new string uses two pointers on char array to swap vowels in place, preserving consonants. Use string.Reverse() to reverse entire string and then replace consonants reverses entire string, losing consonant positions. Use Regex to remove vowels, reverse string, then append vowels at end removes vowels, losing original order. Call ToCharArray(), reverse array, then convert back to string reverses entire string, not selective vowels.
  3. Step 3: Choose best approach

    Convert string to char array, swap vowels using two pointers, then create new string is efficient and correct for selective vowel reversal.
  4. Final Answer:

    Convert string to char array, swap vowels using two pointers, then create new string -> Option B
  5. Quick Check:

    Two-pointer vowel swap preserves consonants [OK]
Hint: Use two pointers on char array to reverse vowels only [OK]
Common Mistakes:
  • Reversing entire string instead of vowels only
  • Removing vowels and losing original order
  • Not converting string to char array before swapping
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