Sponsored
Sponsored
The brute force approach involves scanning the string to find the index of the first occurrence of the character and then reversing the substring from the start to that index. If the character is not found, the string remains unchanged. This approach makes use of two operations: the indexOf
operation which finds the index of the first occurrence of the character and a reversing operation for the substring.
The time complexity is O(n) due to the search and reversal operations. The space complexity is O(n) for the storage of the resulting string.
1using System;
2
3class ReversePrefix {
4 public static string ReversePrefixMethod(string word, char ch) {
5 int idx = word.IndexOf(ch);
6 if (idx == -1) return word;
7 char[] prefixArray = word.Substring(0, idx + 1).ToCharArray();
8 Array.Reverse(prefixArray);
9 return new string(prefixArray) + word.Substring(idx + 1);
10 }
11
12 static void Main() {
13 string word = "abcdxefd";
14 char ch = 'd';
15 Console.WriteLine(ReversePrefixMethod(word, ch));
16 }
17}
This C# solution uses the IndexOf
method to find the character. If found, we convert the substring to an array, reverse it, and then reconstruct the final string by concatenating the reversed part with the rest of the word.
The two-pointers approach is an efficient way to handle the reversed segment directly without using extra space for substring operations. This method entails finding the index of the character first and then reversing the required part of the string in place (where applicable), by gradually swapping elements from both ends of the segment moving inwards.
The time complexity remains O(n) for the search and in-place reversal. The space complexity is O(1) since no extra space proportional to input size is used.
1
This Java solution performs in-place swapping of characters in the array version of the string, by iterating with two pointers moving towards each other until they meet or cross.