Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if String formed by first and last X characters of a String is a Palindrome
Next article icon

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

Last Updated : 27 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
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)


Next Article
Check if String formed by first and last X characters of a String is a Palindrome
author
akashjha2671
Improve
Article Tags :
  • Pattern Searching
  • DSA
  • Arrays
  • Reverse
  • prefix
Practice Tags :
  • Arrays
  • Pattern Searching
  • Reverse

Similar Reads

  • Check if String formed by first and last X characters of a String is a Palindrome
    Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string
    5 min read
  • Minimize length of a string by removing suffixes and prefixes of same characters
    Given a string S of length N consisting only of characters 'a', 'b', and 'c', the task is to minimize the length of the given string by performing the following operations only once: Divide the string into two non-empty substrings and then, append the left substring to the end of the right substring
    6 min read
  • Queries to find first occurrence of a character in a given range
    Given a string S of length N and an array Q[][] of dimension M × 3 consisting of queries of type {L, R, C}, the task is to print the first index of the character C in the range [L, R], if found. Otherwise, print -1. Examples: Input: S= "abcabcabc", Q[][] = { { 0, 3, 'a' }, { 0, 2, 'b' }, { 2, 4, 'z'
    9 min read
  • Find original array from given array which is obtained after P prefix reversals | Set-2
    Given an array arr[] of size N and an integer P, the task is to find the original array from the array obtained by P prefix reversals where in ith reversal the prefix of size i of the array containing indices in range [0, i-1] was reversed. Note: P is less than or equal to N Examples: Input: arr[] =
    7 min read
  • Find frequency of all characters across all substrings of given string
    Given a string S containing all lowercase characters and its length N. Find frequency of all characters across all substrings of the given string. Examples: Input: N = 3, S = "aba"Output: a 6b 4Explanation: The substrings are: a, b, a, ab, ba, aba. The frequency of each character: a = 6, b = 4. Henc
    4 min read
  • Find the Suffix Array of given String with no repeating character
    Given a string str of size N, the task is to find the suffix array of the given string. Note: A suffix array is a sorted array of all suffixes of a given string. Examples: Input: str = "prince"Output: 4 5 2 3 0 1Explanation: The suffixes are0 prince 4 ce1 rince Sort the suffixes 5 e 2 ince ---------
    6 min read
  • Find all strings formed from characters mapped to digits of a number
    Consider below list where each digit from 1 to 9 maps to few characters. 1 -> ['A', 'B', 'C'] 2 -> ['D', 'E', 'F'] 3 -> ['G', 'H', 'I'] 4 -> ['J', 'K', 'L'] 5 -> ['M', 'N', 'O'] 6 -> ['P', 'Q', 'R'] 7 -> ['S', 'T', 'U'] 8 -> ['V', 'W', 'X'] 9 -> ['Y', 'Z'] Given a number,
    11 min read
  • Find repeated character present first in a string
    Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) Examples: Input : geeksforgeeks Output : g (mind that it will be g, not e.) Asked in: Goldman Sachs internship Simple Solution using O(N^2) complexity: The solution is to loop thro
    15 min read
  • Length of String formed by repeating each character in range [L, R] of given string its lexicographic value times
    Given a string S of length N, and a range [L, R] (1 <= L, R <= N). The task is to find the length of string formed by repeating each character in the range [L, R], to its lexicographical value times. Examples: Input: s = "cbbde", l = 2, r = 5Output: 13Explanation: Resultant String is formed af
    9 min read
  • Check if Prefix String exists in the Array
    Given an array of strings, the task is to print "Yes" if it contains a string that is a prefix of another string otherwise, print "No". Examples: Input: arr[] = {"rud", "rudra", "rahi"}Output: YesExplanation: arr[0] = "rud" is a prefix of arr[1] = "rudra", that's why "Yes" is the output. Input: arr[
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences