Reverse Prefix of Word
Problem
You are given a lowercase string word and a single character ch. Locate the first position where ch appears in word and reverse the prefix that runs from index 0 through that position, inclusive; everything after it stays where it is. If ch never appears, return word unchanged.
word = "abcdefd", ch = "d""dcbaefd"def reverse_prefix(word, ch):
j = word.find(ch)
if j == -1:
return word
chars = list(word)
left, right = 0, j
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return "".join(chars)
function reversePrefix(word, ch) {
const j = word.indexOf(ch);
if (j === -1) return word;
const chars = word.split("");
let left = 0, right = j;
while (left < right) {
[chars[left], chars[right]] = [chars[right], chars[left]];
left++;
right--;
}
return chars.join("");
}
String reversePrefix(String word, char ch) {
int j = word.indexOf(ch);
if (j == -1) return word;
char[] chars = word.toCharArray();
int left = 0, right = j;
while (left < right) {
char tmp = chars[left];
chars[left++] = chars[right];
chars[right--] = tmp;
}
return new String(chars);
}
string reversePrefix(string word, char ch) {
size_t j = word.find(ch);
if (j == string::npos) return word;
int left = 0, right = (int)j;
while (left < right) {
swap(word[left], word[right]);
left++;
right--;
}
return word;
}
Explanation
The problem only cares about the first occurrence of ch. Once we know its index j, the task collapses to a classic primitive: reverse the slice word[0..j] in place. Reversing a contiguous range is the textbook two-pointer move, so no extra reversal helpers or slicing tricks are needed.
First we scan from the left (that is exactly what find / indexOf does) until we hit ch. If the scan falls off the end, j = -1 and we return the word untouched — a simple guard clause handles the "character absent" case before any pointer work begins.
Otherwise we set left = 0 and right = j and repeatedly swap the characters under the pointers, moving left forward and right backward. Every swap puts two characters into their final mirrored positions, so the loop needs only about half the prefix length. It stops the moment left >= right: the pointers have met (odd-length prefix, middle character stays put) or crossed (even length). Characters after index j are never touched.
On the default example word = "abcdefd", ch = 'd': the scan finds 'd' at j = 3. Swap word[0] and word[3] ('a' with 'd'), then word[1] and word[2] ('b' with 'c'). Now left = 2 > right = 1, so we stop with "dcbaefd" — the second 'd' at index 6 is irrelevant because only the first occurrence defines the prefix.
The scan looks at each character at most once and the swap loop runs at most (j + 1) / 2 times, so the total work is O(n). Languages with immutable strings (Python, JavaScript, Java) copy the characters into an array first, costing O(n) space; in C++ the string is mutated directly with O(1) extra space.