![]() |
VOOZH | about |
Given an array arr[] of length N consisting of uppercase English letters only and a letter ch. the task is to find the final array that will form by reversing the prefix each time the letter ch is found in the array.
Examples:
Input: arr[] = {'A', 'B', 'X', 'C', 'D', 'X', 'F'}, ch= 'X'
Output: D C X A B X F
Explanation:
First encounter of 'X' at index 2, Initial subarray = A, B, Final subarray = B, A, X.
Second encounter of 'X' at index 5, Initial subarray = B, A, X, C, D
Final subarray = D, C, X, A, B, X(added).
Final subarray after traversing, = D, C, X, A, B, X, FInput: arr[] = {'A', 'B', 'C', 'D', 'E'}, ch = 'F'
Output: A B C D E
Approach: The idea to solve the problem is as follows:
If each portion between two occurrences of ch (or the ends of the array) is considered a segment, then the prefix reversals of the string can be visualised as appending the characters of a segment alternatively at the starting and the ending of string and keep expanding outwards.
- So idea is to push the element of the array into back of a list till ch occurs for first time.
- When first ch occurs, push the elements, including ch, to the front of the list till the next ch occurs. Again if ch occurs push the elements to the back of the list, including ch.
- So, the conclusion is that each time ch occurs, you have to change the direction of pushing the elements.
Note: If there is odd number of K in the array, you need to reverse the list as we start pushing element from back.
Follow The steps given below
Below is the implementation of the above approach:
D C X A B X F
Time Complexity: O(N)
Auxiliary Space: O(N)