Removing Subsequence from concatenated Array
Last Updated :
09 Sep, 2023
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();
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Maximize count of Decreasing Consecutive Subsequences from an Array Given an array arr[] consisting of N integers, the task is to find the maximum count of decreasing subsequences possible from an array that satisfies the following conditions: Each subsequence is in its longest possible form.The difference between adjacent elements of the subsequence is always 1. Ex
8 min read
Remove duplicates from Sorted Array Given a sorted array arr[] of size n, the goal is to rearrange the array so that all distinct elements appear at the beginning in sorted order. Additionally, return the length of this distinct sorted subarray.Note: The elements after the distinct ones can be in any order and hold any value, as they
7 min read
Longest increasing sub-sequence formed by concatenating array to itself N times Given an array arr[] of size N, the task is to find the length of the longest increasing subsequence in the array formed by the concatenation of the arr[] to itself at the end N times.Examples: Input: arr[] = {3, 2, 1}, N = 3 Output: 3 Explanation: The array formed by the concatenation - {3, 2, 1, 3
5 min read
Subsequence queries after removing substrings Given two strings A and B, the problem is to find if string B will be a subsequence of string A if we remove the substring [A[i]..A[j]] from string A. Assume that there are Q queries giving the indices i and j and each query is independent of the other. Examples: Input : A = abcabcxy, B = acy Q = 2
9 min read
Minimum cost to delete characters from String A to remove any subsequence as String B Given two strings A and B of size N and M respectively, where B is a sub-sequence of A and an array arr[] of size N, where arr[i] is the cost to delete ith character from string A. The task is to find the minimum cost to delete characters from A such that after deletion no subsequence of A is the sa
15+ min read
Minimum concatenation required to get strictly LIS for the given array Given an array A[] of size n where there are only unique elements in the array. We have to find the minimum concatenation required for sequence A to get strictly Longest Increasing Subsequence. For array A[] we follow 1 based indexing. Examples: Input: A = {1, 3, 2} Output: 2 Explanation: We can con
6 min read
What are Subsequences in an Array? Subsequences are a fundamental concept in computer science and programming when working with arrays. A subsequence of an array is a sequence of elements from the array that appear in the same order, but not necessarily consecutively. In this blog post, we'll discuss subsequences, covering their defi
6 min read
Generate all distinct subsequences of array using backtracking Given an array arr[] consisting of N positive integers, the task is to generate all distinct subsequences of the array. Examples: Input: arr[] = {1, 2, 2}Output: {} {1} {1, 2} {1, 2, 2} {2} {2, 2}Explanation:The total subsequences of the given array are {}, {1}, {2}, {2}, {1, 2}, {1, 2}, {2, 2}, {1,
7 min read
Print all subsequences of a string using ArrayList Given a string str, the task is to print all the sub-sequences of str. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.Examples: Input: str = "abc" Output: a b ab c ac bc abcInput: str = "geek"
8 min read
Count Permutations in a Sequence Given an array A consisting of N positive integers, find the total number of subsequences of the given array such that the chosen subsequence represents a permutation. Note: Sequence A is a subsequence of B if A can be obtained from B by deleting some(possibly, zero) elements without changing its or
5 min read