Solved! Leetcode 2000. Reverse Prefix of Word

Description: Reverse Prefix of Word

Given a 0-indexed string word and a character chreverse 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

Example 2

Example 3

Constraints

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

Solution

Time Complexity

O(n), where n is the number of characters in the word (specifically O(n/2))

Space Complexity

O(n), where n is the number of characters in the word

Rate this post

Leave a Reply