Similar Problems
Similar Problems not available
Reverse Prefix Of Word - Leetcode Solution
Companies:
LeetCode: Reverse Prefix Of Word Leetcode Solution
Difficulty: Easy
Topics: string two-pointers
Problem:
You are given a zero-indexed string s and an array of integers indices of the same length.
The string s will be some permutation of the characters in the alphabet {'a', 'b', 'c', ..., 'z'}.
For each indices[i], you need to reverse the order of the first indices[i] characters in the substring starting at index 0 and ending at index indices[i] inclusive in s.
For example, if s = "abcdefg" and indices = [2,5,1,6], then you need to reverse the substring "ab" at index 0, the substring "fe" at index 5, the substring "c" at index 1, and the substring "g" at index 6, resulting in the final string "gfedcba".
Return the resulting string.
Example 1:
Input: s = "abcdefg", indices = [2,5,1,6] Output: "gfedcba" Explanation:
- Reversing the substring "ab" at index 2 results in "bacdefg".
- Reversing the substring "fe" at index 5 results in "bacdfeg".
- Reversing the substring "c" at index 1 results in "bacdfeg".
- Reversing the substring "g" at index 6 results in "bacdfeg". Therefore, the resulting string is "gfedcba".
Example 2:
Input: s = "abcd", indices = [0,2] Output: "cbad" Explanation:
- Reversing the substring "a" at index 0 results in "a".
- Reversing the substring "bc" at index 2 results in "cb". Therefore, the resulting string is "cbad".
Solution:
To solve this problem, we can iterate through the indices and at each index, we can reverse the substring from 0 to the current index in the string s. To reverse a substring, we can use two pointers, one pointing to the start of the substring and the other to the end of the substring, and we can swap the characters at these two pointers until they meet in the middle.
Here is the step by step solution:
-
Convert the given string s into a list of characters.
-
Iterate through the indices array and for each index i, reverse the substring s[0:i+1] using a two-pointer approach.
-
Convert the list of characters back to a string and return the result.
Time Complexity:
Since we are iterating through the array of indices and reversing the substring at each index, the time complexity of this algorithm is O(n^2), where n is the length of the string s.
Space Complexity:
We are creating a list of characters from the given string, so the space complexity of this algorithm is O(n), where n is the length of the string s.
Here is the Python code for this solution:
class Solution: def reversePrefix(self, word: str, k: int) -> str: s = list(word) for i in range(k): left = i right = k while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 return ''.join(s)
Reverse Prefix Of Word Solution Code
1