Leetcode 2000. Reverse Prefix of Word
2000. Reverse Prefix of Word
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at the start of the string and ends at the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.
Return the resulting string.
Input: word = "abcdefd", ch = 'd'
Output: "dcbaefd"
Input: word = "xyxzxe", ch = 'z'
Output: "zxyxxe"
Input: word = "abcd", ch = 'z'
Output: "abcd"
word string?
word is in the range [1, 250].word?
word unchanged.ch in the string word.word to the index of ch.find to locate the index of ch in word.ch is not found, return word as is.ch is found, reverse the substring from the beginning of word to the index (inclusive).#include <iostream>
#include <string>
#include <algorithm> // For std::reverse
std::string reversePrefix(std::string word, char ch) {
// Find the first occurrence of ch
size_t index = word.find(ch);
// If ch is found, reverse the prefix
if (index != std::string::npos) {
// Reverse the substring from the beginning to the index, inclusive
std::reverse(word.begin(), word.begin() + index + 1);
}
// Return the modified word (or the original word if ch was not found)
return word;
}
// Example usage
int main() {
std::string word = "abcdefd";
char ch = 'd';
std::cout << reversePrefix(word, ch) << std::endl; // Output: "dcbaefd"
word = "xyxzxe";
ch = 'z';
std::cout << reversePrefix(word, ch) << std::endl; // Output: "zxyxxe"
word = "abcd";
ch = 'z';
std::cout << reversePrefix(word, ch) << std::endl; // Output: "abcd"
return 0;
}
find function runs in O(n) time, where n is the length of the string word.reverse function also runs in O(k) time, where k is the length of the prefix being reversed. In the worst case, k = n.Combining both, the overall time complexity is O(n).
word is modified and returned, but no additional data structures proportional to the input size are utilized.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?