Given a 0-indexed string word and a character ch, reverse the segment of word that starts at the 0 index and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing to the 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 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 do nothing to the string.
Constraints:
1 <= word.length <= 250word consists of lowercase English letters.ch is a lowercase English letter.word contain duplicate characters?
ch character is not in word, should we simply return the original word?
ch is not found in the string, return the string as is.word consists of lowercase English letters, and ch is a lowercase English letter.ch in word:
index to find the position of ch. If ch is not found, handle the ValueError and return the original word.ch is not present in word.word only contains one character.ch is at the very start of word.def reversePrefix(word: str, ch: str) -> str:
try:
# Find index of first occurrence of ch
idx = word.index(ch)
# Slice the word into two parts and reverse the first part
return word[:idx + 1][::-1] + word[idx + 1:]
except ValueError:
# If ch is not found, return word as is
return word
# Test cases
print(reversePrefix("abcdefd", "d")) # Output: "dcbaefd"
print(reversePrefix("xyxzxe", "z")) # Output: "zxyxxe"
print(reversePrefix("abcd", "z")) # Output: "abcd"
n is the length of the string word. This is primarily due to the slicing and reversing operations which each take O(k) time for the prefix of length k.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?