Talentd
FleetCode
Make and follow sheets.Sign in

Reverse Prefix of Word solution and explanation

EasyStackStringTwo Pointers5 min read86.3% acceptanceUpdated 9 Apr 2026
Reverse Prefix of Word (LeetCode 2000) | Full Solution with stack data structureNikhil Lohia · 9:36 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. Reverse Prefix of Word (LeetCode 2000) | Full Solution with stack data structureNikhil Lohia · 9:36 · 2K views
  2. 2000. Reverse Prefix of Word | LEETCODE EASYcode Explainer · 4:45 · 934 views
  3. Reverse Prefix of Word | LeetCode 2000 | EnglishCodeClips with Abhishek Ranjan · 5:40 · 833 views
  4. 2000. Reverse Prefix of Word (Leetcode Easy)Programming Live with Larry · 2:47 · 576 views
  5. Leetcode Solution - 2000 Reverse Prefix of WordJohn Leonardo · 6:58 · 490 views
  6. Leetcode 2000: Reverse Prefix of WordAlgorithms Casts · 7:18 · 388 views
  7. LeetCode 2000 : Reverse Prefix of Word || EASY || C++ || JAVA || Detailed SolutionCodeGPT · 7:48 · 353 views
  8. Reverse Prefix of Word | Leetcode 2000 | Amazon Google Facebook interview questionSuper Lazy Coder · 14:26 · 212 views
  9. LeetCode Reverse Prefix of Word | LeetCode 2000 | JavaScript Sliding WindowSantamaria Code · 7:50 · 138 views
  10. Leetcode solving 2000. Reverse Prefix of WordMath Geeks · 2:18 · 75 views

The problem

Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.

  • For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".

Return the resulting string.

Example 1:

Input: word = "abcdefd", ch = "d"
Output: "dcbaefd"
Explanation: The first occurrence of "d" is at index 3. 
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".

Example 2:

Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first and only occurrence of "z" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".

Example 3:

Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: "z" does not exist in word.
You should not do any reverse operation, the resulting string is "abcd".

Constraints:

  • 1 <= word.length <= 250
  • word consists of lowercase English letters.
  • ch is a lowercase English letter.

Approach overview

Problem Overview: Given a string word and a character ch, reverse the substring from the start of the string up to the first occurrence of ch. If the character does not exist in the string, return the original word unchanged.

Approach 1: Brute Force with Stack (O(n) time, O(n) space)

The straightforward method scans the string to locate the first index of ch. Once found, push characters from index 0 through that index into a stack. Pop elements from the stack to build the reversed prefix, then append the remainder of the string unchanged. The stack naturally reverses order through LIFO operations. This approach is simple to reason about and clearly demonstrates the prefix reversal logic, though it requires extra memory proportional to the prefix length.

This technique works well if you are already comfortable with stack-based reversal patterns. However, the additional memory allocation is unnecessary because the operation can be performed directly on the string or character array.

Approach 2: Two Pointers (O(n) time, O(1) space)

The optimal solution first finds the index of the first occurrence of ch by iterating through the string once. If the character exists, reverse the prefix between indices 0 and idx using the classic two pointers pattern. Initialize one pointer at the beginning and the other at the found index, then swap characters while moving both pointers toward the center.

This method performs the reversal in-place on the character array representation of the string. Each character participates in at most one swap, so the total work remains linear. The key insight is that you only need to reverse a single contiguous segment rather than constructing a new string.

Recommended for interviews: The two pointers approach is what interviewers expect. It shows you recognize a classic in-place reversal pattern and can reduce auxiliary space to O(1). Explaining the brute force stack method first demonstrates understanding of the problem mechanics, but implementing the two-pointer reversal shows stronger algorithmic judgment.

Approach 1: Brute Force Approach

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.

def reversePrefix(word, ch):
    idx = word.find(ch)
    if idx == -1:
        return word
    return word[:idx+1][::-1] + word[idx+1:]

word = "abcdxefd"
ch = 'd'
print(reversePrefix(word, ch))
public class ReversePrefix {
    public static String reversePrefix(String word, char ch) {
        int idx = word.indexOf(ch);
        if (idx == -1) return word;
        StringBuilder prefix = new StringBuilder(word.substring(0, idx + 1));
        prefix.reverse();
        return prefix.toString() + word.substring(idx + 1);
    }

    public static void main(String[] args) {
        String word = "abcdxefd";
        char ch = 'd';
        System.out.println(reversePrefix(word, ch));
    }
}
#include <iostream>
#include <string>
using namespace std;

string reversePrefix(string word, char ch) {
    int n = word.length();
    int idx = word.find(ch);
    if (idx == string::npos) {
        return word;
    }
    reverse(word.begin(), word.begin() + idx + 1);
    return word;
}

int main() {
    string word = "abcdxefd";
    char ch = 'd';
    cout << reversePrefix(word, ch) << endl;
    return 0;
}
function reversePrefix(word, ch) {
    let idx = word.indexOf(ch);
    if (idx === -1) return word;
    return word.slice(0, idx + 1).split('').reverse().join('') + word.slice(idx + 1);
}

let word = "abcdxefd";
let ch = 'd';
console.log(reversePrefix(word, ch));
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* reversePrefix(char* word, char ch) {
    int n = strlen(word);
    int i;
    for (i = 0; i < n; i++) {
        if (word[i] == ch) {
            break;
        }
    }
    if (i == n) return word; // character ch not found
    
    char* result = (char*)malloc((n + 1) * sizeof(char));
    strncpy(result, word, n + 1);
    
    // Reverse operation
    for (int j = 0; j <= i; j++) {
        result[j] = word[i - j];
    }
    return result;
}

int main() {
    char word[] = "abcdxefd";
    char ch = 'd';
    char* result = reversePrefix(word, ch);
    printf("%s\n", result);
    return 0;
}
using System;

class ReversePrefix {
    public static string ReversePrefixMethod(string word, char ch) {
        int idx = word.IndexOf(ch);
        if (idx == -1) return word;
        char[] prefixArray = word.Substring(0, idx + 1).ToCharArray();
        Array.Reverse(prefixArray);
        return new string(prefixArray) + word.Substring(idx + 1);
    }

    static void Main() {
        string word = "abcdxefd";
        char ch = 'd';
        Console.WriteLine(ReversePrefixMethod(word, ch));
    }
}

In this Python solution, we use the find method to locate the character. If found, we perform the reversal using slicing and concatenation to get the final result.

Complexity

The time complexity is O(n) due to finding and slicing operations. The space complexity is O(n) since a new string is created.

Try this approach in the editor

Approach 2: Two Pointers Approach

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.

def reversePrefix(word, ch):
    idx = word.find(ch)
    if idx == -1:
        return word
    word_list = list(word)
    left, right = 0, idx
    while left < right:
        word_list[left], word_list[right] = word_list[right], word_list[left]
        left += 1
        right -= 1
    return ''.join(word_list)

word = "abcdxefd"
ch = 'd'
print(reversePrefix(word, ch))
public class ReversePrefix {
    public static String reversePrefix(String word, char ch) {
        int idx = word.indexOf(ch);
        if (idx == -1) return word;
        char[] cArray = word.toCharArray();
        for (int left = 0, right = idx; left < right; left++, right--) {
            char tmp = cArray[left];
            cArray[left] = cArray[right];
            cArray[right] = tmp;
        }
        return new String(cArray);
    }

    public static void main(String[] args) {
        String word = "abcdxefd";
        char ch = 'd';
        System.out.println(reversePrefix(word, ch));
    }
}
#include <iostream>
#include <string>
using namespace std;

string reversePrefix(string word, char ch) {
    int idx = word.find(ch);
    if (idx == string::npos) return word;
    int left = 0, right = idx;
    while (left < right) {
        swap(word[left], word[right]);
        left++;
        right--;
    }
    return word;
}

int main() {
    string word = "abcdxefd";
    char ch = 'd';
    cout << reversePrefix(word, ch) << endl;
    return 0;
}
function reversePrefix(word, ch) {
    let idx = word.indexOf(ch);
    if (idx === -1) return word;
    let arr = word.split('');
    let left = 0, right = idx;
    while (left < right) {
        [arr[left], arr[right]] = [arr[right], arr[left]];
        left++;
        right--;
    }
    return arr.join('');
}

let word = "abcdxefd";
let ch = 'd';
console.log(reversePrefix(word, ch));
#include <stdio.h>
#include <string.h>

void reverse(char* s, int start, int end) {
    while (start < end) {
        char temp = s[start];
        s[start] = s[end];
        s[end] = temp;
        start++;
        end--;
    }
}

char* reversePrefix(char* word, char ch) {
    int n = strlen(word);
    int i;
    for (i = 0; i < n; i++) {
        if (word[i] == ch) {
            break;
        }
    }
    if (i == n) return word; // character ch not found
    reverse(word, 0, i);
    return word;   
}

int main() {
    char word[] = "abcdxefd";
    char ch = 'd';
    printf("%s\n", reversePrefix(word, ch));
    return 0;
}
using System;

class ReversePrefix {
    public static string ReversePrefixMethod(string word, char ch) {
        int idx = word.IndexOf(ch);
        if (idx == -1) return word;
        char[] arr = word.ToCharArray();
        int left = 0, right = idx;
        while (left < right) {
            char temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
        return new string(arr);
    }

    static void Main() {
        string word = "abcdxefd";
        char ch = 'd';
        Console.WriteLine(ReversePrefixMethod(word, ch));
    }
}

Here, a Python list is used to facilitate in-place character swaps. A two-pointer technique is employed to reverse the identified prefix. Finally, the list is rejoined into a string for the result.

Complexity

With O(n) for both time (traversal and swapping) and O(n) space for the array but in place with respect to actual processed data.

Try this approach in the editor

Approach 3: Simulation

First, we find the index i where the character ch first appears. Then, we reverse the characters from index 0 to index i (including index i). Finally, we concatenate the reversed string with the string starting from index i + 1.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the string word.

function reversePrefix(word: string, ch: string): string {
    const i = word.indexOf(ch) + 1;
    if (!i) {
        return word;
    }
    return [...word.slice(0, i)].reverse().join('') + word.slice(i);
}
func reversePrefix(word string, ch byte) string {
	j := strings.IndexByte(word, ch)
	if j < 0 {
		return word
	}
	s := []byte(word)
	for i := 0; i < j; i++ {
		s[i], s[j] = s[j], s[i]
		j--
	}
	return string(s)
}
impl Solution {
    pub fn reverse_prefix(word: String, ch: char) -> String {
        match word.find(ch) {
            Some(i) => word[..=i].chars().rev().collect::<String>() + &word[i + 1..],
            None => word,
        }
    }
}
class Solution {
    /**
     * @param String $word
     * @param String $ch
     * @return String
     */
    function reversePrefix($word, $ch) {
        $len = strlen($word);
        $rs = '';
        for ($i = 0; $i < $len; $i++) {
            $rs = $rs . $word[$i];
            if ($word[$i] == $ch) {
                break;
            }
        }
        if (strlen($rs) == $len && $rs[$len - 1] != $ch) {
            return $word;
        }
        $rs = strrev($rs);
        $rs = $rs . substr($word, strlen($rs));
        return $rs;
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Brute Force Approach

The time complexity is O(n) due to finding and slicing operations. The space complexity is O(n) since a new string is created.

Two Pointers Approach

With O(n) for both time (traversal and swapping) and O(n) space for the array but in place with respect to actual processed data.

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force with StackO(n)O(n)Useful for understanding prefix reversal logic or when demonstrating stack-based string manipulation.
Two Pointers (Optimal)O(n)O(1)Best for interviews and production code when you want an in-place reversal without extra memory.

Frequently asked questions

Is Reverse Prefix of Word easy or hard?

Reverse Prefix of Word is classified as an Easy problem. The main challenge is recognizing that only the prefix up to the first occurrence of the character needs reversal and applying a standard two pointers string reversal pattern.

Reverse Prefix of Word Python/Java solution

Most implementations convert the string to a character array, locate the first occurrence of the target character, and perform an in-place reversal. This logic works consistently across Python, Java, C++, JavaScript, and other languages with O(n) time complexity.

How to solve Reverse Prefix of Word in O(n)?

Scan the string to locate the first occurrence of the given character. If found, use two pointers starting at index 0 and the found index to swap characters until the pointers meet. This reverses the prefix in place and processes each character at most once.

What is the best approach for Reverse Prefix of Word?

The two pointers approach is the best solution. First find the index of the target character, then reverse the prefix between index 0 and that position using two pointers moving inward. This runs in O(n) time with O(1) extra space.

Is Reverse Prefix of Word asked at Google/Amazon/Meta?

String manipulation problems using two pointers frequently appear in interviews at companies like Amazon, Google, and Meta. While this exact problem may vary, the underlying pattern of prefix reversal and in-place string operations is commonly tested.

What data structure is used in Reverse Prefix of Word?

The problem primarily uses string manipulation with the two pointers technique. A stack can also be used in a brute force solution to reverse the prefix, but the optimal approach operates directly on the character array with constant extra space.

What is the time complexity of Reverse Prefix of Word?

The optimal solution runs in O(n) time where n is the length of the string. One pass finds the first occurrence of the character and another partial pass performs the in-place reversal. Space complexity can be O(1) when using the two pointers technique.

Comments

Now write it yourselfClose this page and solve Reverse Prefix of Word in the editor, without looking.
Practise Reverse Prefix of Word