Reverse Prefix of Word
Description
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. 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 prefix [0..3]: "abcd" -> "dcba". Result: "dcba" + "efd" = "dcbaefd".
Example 2:
Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first 'z' is at index 3. Reverse prefix [0..3]: "xyxz" -> "zxyx". Result: "zxyx" + "xe" = "zxyxxe".
Example 3:
Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: 'z' does not exist in word, so return original string.
Constraints
1 <= word.length <= 250word consists of lowercase English lettersch is a lowercase English letter
Signature
...Complexity
- Time:
O(n) - Space:
O(n)
Hints
- Pattern
- Find index then two-pointer reverse
- Approach
- Find first occurrence of ch. If found, reverse substring from index 0 to that index using two pointers.
- Complexity
- First find ch, then reverse prefix using two pointers
Solutions
=
, = 0,
, = ,
+= 1
-= 1
break
return