Open In App

Find Array formed by reversing Prefix each time given character is found

Last Updated : 27 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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, F

Input: 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++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Final string after performing all the
// operations
 
list<char> findFinalString(char* arr, int n, char ch)
{
    list<char> li;
    bool found = 0;
 
    for (int i = 0; i < n; i++) {
 
        // ch Found
        if (arr[i] == ch)
            found = !found;
 
        // Push character at front of list
        if (found)
            li.push_front(arr[i]);
 
        // Push character at back of list
        else
            li.push_back(arr[i]);
    }
 
    // If there is odd number of ch
    if (found == 1)
        li.reverse();
 
    // Return the list
    return li;
}
 
// Driver Code
int main()
{
    char arr[] = { 'A', 'B', 'X', 'C', 'D', 'X', 'F' };
    char ch = 'X';
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    list<char> ans = findFinalString(arr, N, ch);
    for (auto itr = ans.begin();
         itr != ans.end(); itr++)
        cout << *itr << " ";
 
    return 0;
}


Java




// Java code to implement the above approach
import java.util.ArrayList;
import java.util.Collections;
 
class GFG {
 
  // Final string after performing all the
  // operations
  static ArrayList<Character> findFinalString(char[] arr, int n, char ch) {
    ArrayList<Character> li = new ArrayList<Character>();
    Boolean found = false;
 
    for (int i = 0; i < n; i++) {
 
      // ch Found
      if (arr[i] == ch)
        found = !found;
 
      // Push character at front of list
      if (found)
        li.add(0, arr[i]);
 
      // Push character at back of list
      else
        li.add(arr[i]);
    }
 
    // If there is odd number of ch
    if (found == true)
      Collections.reverse(li);
 
    // Return the list
    return li;
  }
 
  // Driver Code
  public static void main(String args[]) {
    char arr[] = { 'A', 'B', 'X', 'C', 'D', 'X', 'F' };
    char ch = 'X';
    int N = arr.length;
 
    // Function call
    ArrayList<Character> ans = findFinalString(arr, N, ch);
    for (char itr : ans)
      System.out.print(itr + " ");
 
  }
}
 
// This code is contributed by saurabh_jaiswal.


Python3




# Python code to implement the above approach
 
# Final string after performing all the
# operations
def findFinalString(arr, n, ch):
    li = []
    found = 0
    for i in range(n):
       
        # ch found
        if arr[i] == ch:
            found = 1-found
 
        # Push character at front of list
        if found:
            li.insert(0, arr[i])
        # Push character at back of list
        else:
            li.append(arr[i])
 
         #  If there is odd number of ch
    if found == 1:
        li = li[::-1]
 
        # Return the list
    return li
 
#  Driver Code
if __name__ == "__main__":
    arr = ['A', 'B', 'X', 'C', 'D', 'X', 'F']
    ch = 'X'
    N = len(arr)
 
    # Function call
    ans = findFinalString(arr, N, ch)
    for val in ans:
        print(val, end=" ")
         
# This Code is Contributed By Vivek Maddeshiya


C#




using System;
using System.Collections.Generic;
 
// C# code to implement the above approach
public class GFG
{
 
  // Final string after performing all the
  // operations
  public static List<char> findFinalString(char[] arr,
                                           int n, char ch)
  {
    List<char> li = new List<char>();
    bool found = false;
 
    for (int i = 0; i < n; i++) {
 
      // ch Found
      if (arr[i] == ch)
        found = !found;
 
      // Push character at front of list
      if (found == true)
        li.Insert(0, arr[i]);
 
      // Push character at back of list
      else
        li.Add(arr[i]);
    }
 
    // If there is odd number of ch
    if (found == true)
      li.Reverse();
 
    // Return the list
    return li;
  }
 
  // Driver Code
  static public void Main()
  {
 
    char[] arr = { 'A', 'B', 'X', 'C', 'D', 'X', 'F' };
    char ch = 'X';
    int N = arr.Length;
 
    // Function call
    List<char> ans = new List<char>();
    ans = findFinalString(arr, N, ch);
    for (int i = 0; i < ans.Count; i++) {
      Console.Write(" ");
      Console.Write(ans[i]);
    }
  }
}
 
// This code is contributed by akashish__


Javascript




// JavaScript code to implement the above approach
 
// Final string after performing all the
// operations
function findFinalString(arr, n, ch) {
  let li = [];
  let found = 0;
 
  for (let i = 0; i < n; i++) {
    // ch Found
    if (arr[i] == ch) found = !found;
 
    // Push character at front of list
    if (found) li.unshift(arr[i]);
    // Push character at back of list
    else li.push(arr[i]);
  }
 
  // If there is odd number of ch
  if (found == 1) li.reverse();
 
  // Return the list
  return li;
}
 
// Driver Code
 
let arr = ["A", "B", "X", "C", "D", "X", "F"];
let ch = "X";
let N = 7;
 
// Function call
let ans = findFinalString(arr, N, ch);
console.log(ans);
 
// This code is contributed by ishankhandelwals.


Output

D C X A B X F 

Time Complexity: O(N)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads