

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
- Â Create a list named li to store the elements
- Â Create a variable named found to check which side you have to add the elements from
- Â If ch occurs flip the value of found from 1 to 0 or 0 to 1.
- If found is equal to 1 add the elements to the front.Â
- Else add the elements to the back
- Â If ch occurs odd number of times reverse the list and print, else print it simplyÂ
Below is the implementation of the above approach:
C++
|
Time Complexity: O(N)
Auxiliary Space: O(N)