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.
1#include <iostream>
2#include <string>
3using namespace std;
4
5string reversePrefix(string word, char ch) {
6 int n = word.length();
7 int idx = word.find(ch);
8 if (idx == string::npos) {
9 return word;
10 }
11 reverse(word.begin(), word.begin() + idx + 1);
12 return word;
13}
14
15int main() {
16 string word = "abcdxefd";
17 char ch = 'd';
18 cout << reversePrefix(word, ch) << endl;
19 return 0;
20}
The solution in C++ uses the standard library functions to find the index of the first occurrence of the character and if found, it reverses the prefix of the string using the reverse function. The result is then outputted.
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.