Leetcode 2000 Reverse Prefix of Word

Intuition

Find position of ch (if any) then use two pointers to swap characters until string is reveresed from beginning to index of ch

Approach

Start by checking each character for ch. If we find it, that's where our right pointer will start. Our left pointer will start at the beginning of the string.

While left is less than right swap characters and then decrement right, and increment left. When they meet the substring beginning at index 0 and ending at the index of ch will be reversed.

Code

public class Solution 
{
    public string ReversePrefix(string word, char ch) 
    {
        var arr = word.ToCharArray();
        int left = 0;
        int right = 0;
        //find pos of ch if it exists
        while(right < arr.Length && arr[right] != ch)
        {
           right++;
        }
        if(right == arr.Length)
        {
            //if not return the original word
            return word;
        }

        //two pointers, one at ch, the other at the start of the string
        while(left < right)
        {
           //swap the two characters, increase the left pointer, decrease the right
           var temp = arr[left];
           arr[left] = arr[right];
           arr[right] = temp;
           left++;
           right--; 
        }
        //when both pointers meet, return
        return new string(arr);

    }
}