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.
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.A brute force solution would involve iterating through the string to find the index of the character ch
. If found, reverse the substring from index 0 to that index (inclusive). If not found, return the original string.
def reverse_prefix_brute_force(word: str, ch: str) -> str:
index = -1
for i in range(len(word)):
if word[i] == ch:
index = i
break
if index == -1:
return word
reversed_substring = word[:index+1][::-1]
return reversed_substring + word[index+1:]
O(N) in the worst case, where N is the length of the string word
. This is because we iterate through the string once to find the character ch
and then potentially reverse a portion of the string, which also takes O(N) time.
O(N). In the worst case, we create a new reversed substring of length N.
The optimal solution is essentially the same as the brute force one, but can be written more concisely. The core logic remains the same:
ch
.ch
isn't found, return the original string.ch
.def reverse_prefix_optimal(word: str, ch: str) -> str:
try:
index = word.index(ch)
return word[:index+1][::-1] + word[index+1:]
except ValueError:
return word
O(N), where N is the length of the string word
. The word.index(ch)
operation takes O(N) time in the worst case. The string slicing and reversal also contribute O(N) operations.
O(N). String slicing creates a copy of the string or a portion of it.
ch
is the first character, the entire string up to that point (just the first character) is reversed (which results in the same string).ch
is the last character, the entire string is reversed.