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.
1function reversePrefix(word, ch) {
2 let idx = word.indexOf(ch);
3 if (idx === -1) return word;
4 return word.slice(0, idx + 1).split('').reverse().join('') + word.slice(idx + 1);
5}
6
7let word = "abcdxefd";
8let ch = 'd';
9console.log(reversePrefix(word, ch));
In JavaScript, we use the indexOf
method to locate the character index and the slice
, split
, reverse
, and join
methods to reverse the required portion of the string, then concatenate it with the rest of the unchanged 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
The JavaScript solution uses array split/join to help with character swapping using two pointers, reversing only the portion necessary and concatenating in the final step.