#2000

Reverse Prefix of Word

Easy
Two PointersStringStackTwo PointersString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a single pass to find the index of 'ch' and then constructs the result in one go, making it more efficient. This reduces the number of operations needed to reverse the substring.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable to store the index of the first occurrence of 'ch'.
  2. 2Step 2: Loop through 'word' to find the index of 'ch'.
  3. 3Step 3: If 'ch' is not found, return 'word' as is.
  4. 4Step 4: Create a new string by reversing the substring from index 0 to the found index and appending the rest of 'word'.
  5. 5Step 5: Return the resulting string.
solution.py5 lines
1def reversePrefix(word, ch):
2    index = word.find(ch)
3    if index == -1:
4        return word
5    return ''.join(reversed(word[:index + 1])) + word[index + 1:]

Complexity note: The time complexity is O(n) because we traverse the string only once to find 'ch' and construct the result. The space complexity is O(n) due to the new string being created.

  • 1Finding the index of the character is crucial for both approaches.
  • 2Reversing a substring can be done efficiently using built-in functions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.