Given a string S of Size N. Initially, the value of count is 0. The task is to find the value of count after N operations to remove all the N characters of the given string S where each operation is:
- In each operation, select alphabetically the smallest character in the string S and remove that character from S and add its index to count.
- If multiple characters are present then remove the character having the smallest index.
Note: Consider string as 1-based indexing.
Examples:
Input: N = 5, S = “abcab”
Output: 8
Explanation:
Remove character ‘a’ then string becomes “bcab” and the count = 1.
Remove character ‘a’ then string becomes “bcb” and the count = 1 + 3 = 4.
Remove character ‘b’ then string becomes “cb” and the count = 4 + 1 = 5.
Remove character ‘b’ then string becomes “c” and the count = 5 + 2 = 7.
Remove character ‘c’ then string becomes “” and the count = 7 + 1 = 8.
Input: N = 5 S = “aabbc”
Output: 5
Explanation:
The value after 5 operations to remove all the 5 characters of String aabbc is 5.
Naive Approach: The idea is to check if the string is empty or not. If it is not empty then following are the steps to solve the problem:
- Find the first occurrence of the smallest alphabets in the current string, let’s say ind and remove it from the string.
- Increase the count by ind + 1.
- Repeat the above step until the string becomes empty.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string>
using namespace std;
void charactersCount(string str, int n)
{
int count = 0;
while (n > 0) {
char cur = str[0];
int ind = 0;
for ( int j = 1; j < n; j++) {
if (str[j] < cur) {
cur = str[j];
ind = j;
}
}
str.erase(str.begin() + ind);
n--;
count += ind + 1;
}
cout << count << endl;
}
int main()
{
string str = "aabbc" ;
int n = 5;
charactersCount(str, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void charactersCount(String str, int n)
{
int count = 0 ;
while (n > 0 )
{
char cur = str.charAt( 0 );
int ind = 0 ;
for ( int j = 1 ; j < n; j++)
{
if (str.charAt(j) < cur)
{
cur = str.charAt(j);
ind = j;
}
}
str = str.substring( 0 , ind) +
str.substring(ind + 1 );
n--;
count += ind + 1 ;
}
System.out.print(count + "\n" );
}
public static void main(String[] args)
{
String str = "aabbc" ;
int n = 5 ;
charactersCount(str, n);
}
}
|
Python3
def charactersCount( str , n):
count = 0 ;
while (n > 0 ):
cur = str [ 0 ];
ind = 0 ;
for j in range ( 1 , n):
if ( str [j] < cur):
cur = str [j];
ind = j;
str = str [ 0 : ind] + str [ind + 1 :];
n - = 1 ;
count + = ind + 1 ;
print (count);
if __name__ = = '__main__' :
str = "aabbc" ;
n = 5 ;
charactersCount( str , n);
|
C#
using System;
class GFG{
static void charactersCount(String str, int n)
{
int count = 0;
while (n > 0)
{
char cur = str[0];
int ind = 0;
for ( int j = 1; j < n; j++)
{
if (str[j] < cur)
{
cur = str[j];
ind = j;
}
}
str = str.Substring(0, ind) +
str.Substring(ind + 1);
n--;
count += ind + 1;
}
Console.Write(count + "\n" );
}
public static void Main(String[] args)
{
String str = "aabbc" ;
int n = 5;
charactersCount(str, n);
}
}
|
Javascript
<script>
function charactersCount(str, n)
{
let count = 0;
while (n > 0)
{
let cur = str[0].charCodeAt();
let ind = 0;
for (let j = 1; j < n; j++)
{
if (str[j].charCodeAt() < cur)
{
cur = str[j].charCodeAt();
ind = j;
}
}
str = str.substring(0, ind) +
str.substring(ind + 1);
n--;
count += ind + 1;
}
document.write(count + "</br>" );
}
let str = "aabbc" ;
let n = 5;
charactersCount(str, n);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: This problem can be solved using the concept of Binary Index Tree or Fenwick Tree. Below are the steps:
- Initially, Store the values of indices of all the characters/alphabet in increasing order.
- Start with the smallest alphabet ‘a’ and remove all ‘a’s in the order of their occurrence. After removing, select the next alphabet ‘b’, and repeat this step until all alphabets are removed.
- Removing the character means that its corresponding value in the array is changed to 0, indicating that it is removed.
- Before removing, find the position of the character in the string using the sum() method in Fenwick Tree and add the position value to the count.
- After removing all the characters in the string, the value of count is obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct FenwickTree {
vector< int > bit;
int n;
FenwickTree( int n)
{
this ->n = n + 1;
bit = vector< int >(n, 0);
}
FenwickTree(vector< int > a)
: FenwickTree(a.size())
{
for ( size_t i = 0; i < a.size(); i++)
add(i, a[i]);
}
int sum( int idx)
{
int ret = 0;
idx = idx + 1;
while (idx > 0) {
ret += bit[idx];
idx -= idx & (-idx);
}
return ret;
}
void add( int idx, int val)
{
idx = idx + 1;
while (idx <= n) {
bit[idx] += val;
idx += idx & (-idx);
}
}
void update( int idx, int val)
{
add(idx, val - valat(idx));
}
int sum( int l, int r)
{
return sum(r) - sum(l - 1);
}
int valat( int i)
{
return sum(i, i);
}
void clr( int sz)
{
bit.clear();
n = sz + 1;
bit.resize(n + 1, 0);
for ( int i = 0; i < n; i++)
add(i, 1);
}
};
void charactersCount(string str, int n)
{
int i, count = 0;
vector<vector< int > > mp
= vector<vector< int > >(26,
vector< int >());
FenwickTree ft = FenwickTree(n);
ft.clr(n);
for (i = 0; i < 26; i++)
mp[i].clear();
i = 0;
for ( char ch : str) {
mp[ch - 'a' ].push_back(i);
i++;
}
for (i = 0; i < 26; i++) {
for ( int ind : mp[i]) {
count += ft.sum(ind);
ft.update(ind, 0);
}
}
cout << count << endl;
}
int main()
{
string str = "aabbc" ;
int n = 5;
charactersCount(str, n);
return 0;
}
|
Java
#include <bits/stdc++.h>
using namespace std;
struct FenwickTree {
vector< int > bit;
int n;
FenwickTree( int n)
{
this ->n = n + 1 ;
bit = vector< int >(n, 0 );
}
FenwickTree(vector< int > a)
: FenwickTree(a.size())
{
for (size_t i = 0 ; i < a.size(); i++)
add(i, a[i]);
}
int sum( int idx)
{
int ret = 0 ;
idx = idx + 1 ;
while (idx > 0 ) {
ret += bit[idx];
idx -= idx & (-idx);
}
return ret;
}
void add( int idx, int val)
{
idx = idx + 1 ;
while (idx <= n) {
bit[idx] += val;
idx += idx & (-idx);
}
}
void update( int idx, int val)
{
add(idx, val - valat(idx));
}
int sum( int l, int r)
{
return sum(r) - sum(l - 1 );
}
int valat( int i)
{
return sum(i, i);
}
void clr( int sz)
{
bit.clear();
n = sz + 1 ;
bit.resize(n + 1 , 0 );
for ( int i = 0 ; i < n; i++)
add(i, 1 );
}
};
void charactersCount(string str, int n)
{
int i, count = 0 ;
vector<vector< int > > mp
= vector<vector< int > >( 26 ,
vector< int >());
FenwickTree ft = FenwickTree(n);
ft.clr(n);
for (i = 0 ; i < 26 ; i++)
mp[i].clear();
i = 0 ;
for ( char ch : str) {
mp[ch - 'a' ].push_back(i);
i++;
}
for (i = 0 ; i < 26 ; i++) {
for ( int ind : mp[i]) {
count += ft.sum(ind);
ft.update(ind, 0 );
}
}
cout << count << endl;
}
int main()
{
string str = "aabbc" ;
int n = 5 ;
charactersCount(str, n);
return 0 ;
}
|
C#
using System;
using System.Collections.Generic;
class GFG{
public class FenwickTree
{
public int []bit;
int n;
public FenwickTree( int n)
{
this .n = n + 1;
bit = new int [n];
}
public FenwickTree(List< int > a)
{
for ( int i = 0; i < a.Count; i++)
add(i, a[i]);
}
public int sum( int idx)
{
int ret = 0;
idx = idx + 1;
while (idx > 0)
{
ret += bit[idx];
idx -= idx & (-idx);
}
return ret;
}
public void add( int idx, int val)
{
idx = idx + 1;
while (idx <= n)
{
bit[idx] += val;
idx += idx & (-idx);
}
}
public void update( int idx, int val)
{
add(idx, val - valat(idx));
}
public int sum( int l, int r)
{
return sum(r) - sum(l - 1);
}
public int valat( int i)
{
return sum(i, i);
}
public void clr( int sz)
{
n = sz + 1;
bit = new int [n + 1];
for ( int i = 0; i < n; i++)
add(i, 1);
}
};
static void charactersCount(String str, int n)
{
int i, count = 0;
List< int > []mp = new List< int >[26];
for (i = 0; i < mp.Length; i++)
mp[i] = new List< int >();
FenwickTree ft = new FenwickTree(n);
ft.clr(n);
for (i = 0; i < 26; i++)
mp[i].Clear();
i = 0;
foreach ( char ch in str.ToCharArray())
{
mp[ch - 'a' ].Add(i);
i++;
}
for (i = 0; i < 26; i++)
{
foreach ( int ind in mp[i])
{
count += ft.sum(ind);
ft.update(ind, 0);
}
}
Console.Write(count + "\n" );
}
public static void Main(String[] args)
{
String str = "aabbc" ;
int n = 5;
charactersCount(str, n);
}
}
|
Javascript
<script>
class FenwickTree
{
constructor(n)
{
this .n = n + 1;
this .bit = new Array(n);
}
_FenwickTree(a)
{
for (let i = 0; i < a.length; i++)
this .add(i, a.get(i));
}
sum(idx)
{
let ret = 0;
idx = idx + 1;
while (idx > 0)
{
ret += this .bit[idx];
idx -= idx & (-idx);
}
return ret;
}
add(idx,val)
{
idx = idx + 1;
while (idx <= this .n)
{
this .bit[idx] += val;
idx += idx & (-idx);
}
}
update(idx,val)
{
this .add(idx, val - this .valat(idx));
}
_sum(l,r)
{
return this .sum(r) - this ._sum(l - 1);
}
valat(i)
{
return this .sum(i, i);
}
clr(sz)
{
this .n = sz + 1;
this .bit = new Array( this .n + 1);
for (let i=0;i< this .n+1;i++)
this .bit[i]=0;
for (let i = 0; i < n; i++)
this .add(i, 1);
}
}
function charactersCount(str,n)
{
let i, count = 0;
let mp = new Array(26);
for (i = 0; i < mp.length; i++)
mp[i] = [];
let ft = new FenwickTree(n);
ft.clr(n);
for (i = 0; i < 26; i++)
mp[i]=[];
i = 0;
for (let ch of str.split( "" ).values())
{
mp[ch.charCodeAt(0) - 'a' .charCodeAt(0)].push(i);
i++;
}
for (i = 0; i < 26; i++)
{
for (let ind of mp[i].values())
{
count += ft.sum(ind);
ft.update(ind, 0);
}
}
document.write(count + "<br>" );
}
let str = "aabbc" ;
let n = 5;
charactersCount(str, n);
</script>
|
Python3
class FenwickTree:
def __init__( self , n):
self .n = n + 1
self .bit = [ 0 ] * self .n
def _FenwickTree( self , a):
for i in range ( len (a)):
self .add(i, a[i])
def sum ( self , idx):
ret = 0
idx = idx + 1
while idx > 0 :
ret + = self .bit[idx]
idx - = idx & ( - idx)
return ret
def add( self , idx, val):
idx = idx + 1
while idx < = self .n:
self .bit[idx] + = val
idx + = idx & ( - idx)
def update( self , idx, val):
self .add(idx, val - self .valat(idx))
def _sum( self , l, r):
return self . sum (r) - self . sum (l - 1 )
def valat( self , i):
return self . sum (i)
def clr( self , sz):
self .n = sz + 1
self .bit = [ 0 ] * ( self .n + 1 )
for i in range (sz):
self .add(i, 1 )
def charactersCount(s, n):
count = 0
mp = [[] for i in range ( 26 )]
ft = FenwickTree(n)
ft.clr(n)
for i, ch in enumerate (s):
mp[ ord (ch) - ord ( 'a' )].append(i)
for i in range ( 26 ):
for ind in mp[i]:
count + = ft. sum (ind)
ft.update(ind, 0 )
print (count)
s = "aabbc"
n = 5
charactersCount(s, n)
|
Time Complexity: O(N*log(N))
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
13 Mar, 2023
Like Article
Save Article