Open In App

Removing Subsequence from concatenated Array

Last Updated : 09 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given array A[] formed by the concatenation of string “ABC” one or multiple times. The task for this problem is to remove all occurrences of subsequence “ABC” by performing the following operation a minimum number of times. In one operation swap any two elements of array A[]. print the number of operations required and elements on which operations are performed in each step.

Examples:

Input: A[] = {‘A’, ‘B’, ‘C’}
Output: 1
1 3
Explanation: Swapping 1’st and 3’rd element of array A[] it becomes A[] = {‘C’, ‘B’, ‘A’} which does not contain “ABC'” as subsequence.

Input: A[] = {‘A’, ‘B’, ‘C’, ‘A’, ‘B’, ‘C’};
Output: 1
1 6

Approach: To solve the problem follow the below idea:

No subsequences of string “ABC” would also mean no substrings of “ABC” in array A[]. it would be also be the lower bound for having no subsequences of string “ABC”.

Swap i-th A from start with i-th C from end for 1 <= i <= ceil(N / 6) We can see that, no substrings of “ABC” exists after performing ceil(N / 6) operations. Since we can only destroy atmost 2 substrings in one operations, ceil(N / 6) is minimum possible. Now if you see clearly, after performing above operations, there does not exist any subsequence of string ABC in original string. Hence ceil(N / 6)  is also the answer for the original problem.

Below are the steps for the above approach:

  • Create variable numberOfOperations.
  • Create two pointers L = 1 and R = N.
  • Create an array eachStep[][2] to store which elements will be replaced at which step.
  • Run a while loop till L < R.
  • Each step push {L, R} to eachStep[][2] then move pointer L to 3 steps forwards and R to 3 steps backward.
  • After while loop ends print the numberOfOperations and eachStep[][2] array.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to remove every occurence of
// subsequence ABC by peforming
// minimum number of swaps
void minimizeOperations(char A[], int N)
{
 
    // Variable that stores nunber of
    // operations required
    int numberOfOperations = ceil(N / 2.0);
 
    // Left and Right pointer of array
    int L = 1, R = N;
 
    // To store answer of each step
    vector<pair<int, int> > eachStep;
 
    // Store operation on each step
    while (L < R) {
 
        // L and R will be swaped
        // in next step
        eachStep.push_back({ L, R });
 
        // Move pointers for next operation
        L += 3;
        R -= 3;
    }
 
    // Printing number of operations
    cout << numberOfOperations << endl;
 
    // Each step of operation
    for (auto ans : eachStep)
        cout << ans.first << " " << ans.second << endl;
 
    // Next line
    cout << endl
         << endl;
}
 
// Driver Code
int32_t main()
{
 
    // Input 1
    int N = 3;
    char A[] = { 'A', 'B', 'C' };
 
    // Function Call
    minimizeOperations(A, N);
 
    // Input 2
    int N1 = 6;
    char A1[] = { 'A', 'B', 'C', 'A', 'B', 'C' };
 
    // Function Call
    minimizeOperations(A1, N1);
 
    return 0;
}


Java




// Java code to implement the approach
 
import java.util.ArrayList;
 
class GFG {
 
    // Function to remove every occurrence of
    // subsequence ABC by performing
    // a minimum number of swaps
    static void minimizeOperations(char[] A, int N)
    {
 
        // Variable that stores the number of
        // operations required
        int numberOfOperations = (int)Math.ceil(N / 2.0);
 
        // Left and Right pointer of the array
        int L = 1, R = N;
 
        // To store the answer of each step
        ArrayList<ArrayList<Integer> > eachStep
            = new ArrayList<>();
 
        // Store operation on each step
        while (L < R) {
 
            // L and R will be swapped
            // in the next step
            ArrayList<Integer> step = new ArrayList<>();
            step.add(L);
            step.add(R);
            eachStep.add(step);
 
            // Move pointers for the next operation
            L += 3;
            R -= 3;
        }
 
        // Printing the number of operations
        System.out.println(numberOfOperations);
 
        // Each step of the operation
        for (ArrayList<Integer> ans : eachStep)
            System.out.println(ans.get(0) + " "
                               + ans.get(1));
 
        // Next line
        System.out.println("\n\n");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Input 1
        int N = 3;
        char[] A = { 'A', 'B', 'C' };
 
        // Function Call
        minimizeOperations(A, N);
 
        // Input 2
        int N1 = 6;
        char[] A1 = { 'A', 'B', 'C', 'A', 'B', 'C' };
 
        // Function Call
        minimizeOperations(A1, N1);
    }
}
 
// This code is contributed by shivamgupta0987654321


Python3




# python code to implement the approach
 
# Function to remove every occurrence of
# subsequence ABC by performing
# a minimum number of swaps
def minimize_operations(A):
    # Length of the array A
    N = len(A)
 
    # Variable that stores the number of operations required
    number_of_operations = (N + 1) // 2
 
    # Left and Right pointer of array
    L, R = 1, N
 
    # To store the answer of each step
    each_step = []
 
    # Store operation on each step
    while L < R:
        # L and R will be swapped in the next step
        each_step.append((L, R))
 
        # Move pointers for the next operation
        L += 3
        R -= 3
 
    # Printing the number of operations
    print(number_of_operations)
 
    # Each step of operation
    for ans in each_step:
        print(ans[0], ans[1])
 
    # Next line
    print("\n\n")
 
 
# Driver Code
if __name__ == "__main__":
    # Input 1
    A = ['A', 'B', 'C']
    # Function Call
    minimize_operations(A)
 
    # Input 2
    A1 = ['A', 'B', 'C', 'A', 'B', 'C']
    # Function Call
    minimize_operations(A1)


C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
class GFG
{
    // Function to remove every occurrence of
    // subsequence ABC by performing
    // a minimum number of swaps
    static void minimizeOperations(char[] A, int N)
    {
        // Variable that stores the number of
        // operations required
        int numberOfOperations = (int)Math.Ceiling(N / 2.0);
 
        // Left and Right pointer of the array
        int L = 1, R = N;
 
        // To store the answer of each step
        List<List<int>> eachStep = new List<List<int>>();
 
        // Store operation on each step
        while (L < R)
        {
            // L and R will be swapped
            // in the next step
            List<int> step = new List<int>();
            step.Add(L);
            step.Add(R);
            eachStep.Add(step);
 
            // Move pointers for the next operation
            L += 3;
            R -= 3;
        }
 
        // Printing the number of operations
        Console.WriteLine(numberOfOperations);
 
        // Each step of the operation
        foreach (List<int> ans in eachStep)
        {
            Console.WriteLine(ans[0] + " " + ans[1]);
        }
 
        // Next line
        Console.WriteLine("\n\n");
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        // Input 1
        int N = 3;
        char[] A = { 'A', 'B', 'C' };
 
        // Function Call
        minimizeOperations(A, N);
 
        // Input 2
        int N1 = 6;
        char[] A1 = { 'A', 'B', 'C', 'A', 'B', 'C' };
 
        // Function Call
        minimizeOperations(A1, N1);
    }
}
 
 
// This code is contributed by Utkarsh Kumar


Javascript




// Function to remove every occurence of
// subsequence ABC by peforming
// minimum number of swaps
function minimizeOperations(A, N) {
    // Variable that stores number of operations required
    const numberOfOperations = Math.ceil(N / 2);
 
    // Left and Right pointer of array
    let L = 1;
    let R = N;
 
    // To store answer of each step
    const eachStep = [];
 
    // Store operation on each step
    while (L < R) {
        // L and R will be swapped in the next step
        eachStep.push([L, R]);
 
        // Move pointers for the next operation
        L += 3;
        R -= 3;
    }
 
    // Printing number of operations
    console.log(numberOfOperations);
 
    // Each step of operation
    eachStep.forEach((ans) => console.log(ans[0], ans[1]));
 
    // Next line
    console.log('\n\n');
}
 
// Driver Code
function main() {
    // Input 1
    const N = 3;
    const A = ['A', 'B', 'C'];
 
    // Function Call
    minimizeOperations(A, N);
 
    // Input 2
    const N1 = 6;
    const A1 = ['A', 'B', 'C', 'A', 'B', 'C'];
 
    // Function Call
    minimizeOperations(A1, N1);
}
 
main();


Output

2
1 3


3
1 6









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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads