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.
1public class ReversePrefix {
2 public static String reversePrefix(String word, char ch) {
3 int idx = word.indexOf(ch);
4 if (idx == -1) return word;
5 StringBuilder prefix = new StringBuilder(word.substring(0, idx + 1));
6 prefix.reverse();
7 return prefix.toString() + word.substring(idx + 1);
8 }
9
10 public static void main(String[] args) {
11 String word = "abcdxefd";
12 char ch = 'd';
13 System.out.println(reversePrefix(word, ch));
14 }
15}
In the Java solution, we utilize the indexOf method to find the character index. If found, we use a StringBuilder to reverse the substring and concatenate it back with the remaining part of the string.
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 C solution utilizes a helper function to reverse a part of the array in place. We locate the index as before, then swap elements utilizing two pointers starting from both ends of the range and working inwards.