# Minimum cost to remove the spaces between characters of a String by rearranging the characters

Given a string str that consists of characters and spaces, the task is to find the minimum cost to reduce the number of spaces between characters of the string.

Cost of moving a character for index i to index j is defined as: | i – j |

Examples:

Input: str = ” @ \$”
Output:
Explanation:
As the characters are at indices [2, 7] (only two), either move the first character to the nearest second character or vice-versa. The cost required is |2-6| = 4 or |6-2| = 4.
Therefore, the minimum cost is 4.

Input: str = ” A ”
Output:
Explanation:
Since the string consists of only one character, no changes required. Therefore, minimum cost is 0.

Approach: The idea is to move all the characters nearest to the middle of the string so that the overall cost is minimized. Below are the steps:

1. Initialize the total cost with 0.
2. Transverse the string and count the spaces between the two characters.
3. Get both the characters together and add the cost to the total cost.
4. Repeat the above steps for all characters.

Below is the implementation of the above approach:

 `// C++ program to gather characters ` `// of a string in minimum cost ` `#include ` `using` `namespace` `std;`   `// Function to calculate the ` `// minimum cost ` `int` `min_cost(string S)` `{ ` `    `  `    ``// Stores the minimum cost ` `    ``int` `cost = 0;`   `    ``// Stores the count of ` `    ``// characters found ` `    ``int` `F = 0;`   `    ``// Stores the count of ` `    ``// blank spaces found ` `    ``int` `B = 0;`   `    ``int` `count = 0;` `    `  `    ``for``(``char` `c : S)` `        ``if``(c == ``' '``)` `           ``count++;` `           `  `    ``// Stores the count of ` `    ``// total characters` `    ``int` `n = S.size() - count; `   `    ``// If the count of characters ` `    ``// is equal to 1 ` `    ``if` `(n == 1) ` `        ``return` `cost;`   `    ``// Iterate over the string ` `    ``for``(``char` `in : S)` `    ``{ ` `        `  `        ``// Consider the previous character ` `        ``// together with current character ` `        ``if` `(in != ``' '``)` `        ``{` `            ``// If not together already ` `            ``if` `(B != 0)` `            ``{` `                `  `                ``// Add the cost to group ` `                ``// them together ` `                ``cost += min(n - F, F) * B;` `                ``B = 0;` `            ``}` `            `  `            ``// Increase count of ` `            ``// characters found ` `            ``F += 1;` `        ``}` `        `  `        ``// Otherwise ` `        ``else` `        ``{ ` `            `  `            ``// Increase count of ` `            ``// spaces found ` `            ``B += 1;` `        ``} ` `    ``}` `    `  `    ``// Return the total ` `    ``// cost obtained ` `    ``return` `cost;` `}`   `// Driver Code` `int` `main ()` `{` `    ``string S = ``" @    \$"``;` `    `  `    ``cout << min_cost(S);` `    ``return` `0;` `}`   `// This code is contributed by Amit Katiyar`

 `// Java program to gather characters ` `// of a string in minimum cost ` `import` `java.util.*;` `import` `java.lang.*;`   `class` `GFG{`   `// Function to calculate the ` `// minimum cost ` `static` `int` `min_cost(String S)` `{ ` `    `  `    ``// Stores the minimum cost ` `    ``int` `cost = ``0``;`   `    ``// Stores the count of ` `    ``// characters found ` `    ``int` `F = ``0``;`   `    ``// Stores the count of ` `    ``// blank spaces found ` `    ``int` `B = ``0``;`   `    ``int` `count = ``0``;` `    `  `    ``for``(``char` `c : S.toCharArray())` `        ``if``(c == ``' '``)` `           ``count++;` `           `  `    ``// Stores the count of ` `    ``// total characters` `    ``int` `n = S.length() - count; `   `    ``// If the count of characters ` `    ``// is equal to 1 ` `    ``if` `(n == ``1``) ` `        ``return` `cost;`   `    ``// Iterate over the string ` `    ``for``(``char` `in : S.toCharArray())` `    ``{ ` `        `  `        ``// Consider the previous character ` `        ``// together with current character ` `        ``if` `(in != ``' '``)` `        ``{` `            ``// If not together already ` `            ``if` `(B != ``0``)` `            ``{` `                `  `                ``// Add the cost to group ` `                ``// them together ` `                ``cost += Math.min(n - F, F) * B;` `                ``B = ``0``;` `            ``}` `            `  `            ``// Increase count of ` `            ``// characters found ` `            ``F += ``1``;` `        ``}` `        `  `        ``// Otherwise ` `        ``else` `        ``{ ` `            `  `            ``// Increase count of ` `            ``// spaces found ` `            ``B += ``1``;` `        ``} ` `    ``}` `    `  `    ``// Return the total ` `    ``// cost obtained ` `    ``return` `cost;` `}`   `// Driver Code` `public` `static` `void` `main (String[] args)` `{` `    ``String S = ``" @    \$"``;` `    `  `    ``System.out.println(min_cost(S));` `}` `}`   `// This code is contributed by offbeat`

 `# Python3 program to gather characters` `# of a string in minimum cost`   `# Function to calculate the` `# minimum cost` `def` `min_cost(S):`   `    ``# Stores the minimum cost` `    ``cost ``=` `0`   `    ``# Stores the count of` `    ``# characters found ` `    ``F ``=` `0`   `    ``# Stores the count of` `    ``# blank spaces found ` `    ``B ``=` `0`   `    ``# Stores the count of` `    ``# total characters` `    ``n ``=` `len``(S)``-``S.count(``' '``)`   `    ``# If the count of characters` `    ``# is equal to 1` `    ``if` `n ``=``=` `1``:` `        ``return` `cost`   `    ``# Iterate over the string` `    ``for` `char ``in` `S:`   `        ``# Consider the previous character ` `        ``# together with current character` `        ``if` `char !``=` `' '``:`   `            ``# If not together already` `            ``if` `B !``=` `0``:` `                `  `                ``# Add the cost to group` `                ``# them together` `                ``cost ``+``=` `min``(n ``-` `F, F) ``*` `B` `                ``B ``=` `0` `                `  `            ``# Increase count of ` `            ``# characters found` `            ``F ``+``=` `1` `            `  `        ``# Otherwise` `        ``else``:` `            `  `            ``# Increase count of ` `            ``# spaces found` `            ``B ``+``=` `1` `            `  `    ``# Return the total` `    ``# cost obtained` `    ``return` `cost`     `# Driver Code` `S ``=` `" @    \$"` `print``(min_cost(S))`

 `// C# program to gather characters ` `// of a string in minimum cost ` `using` `System;`   `class` `GFG{`   `// Function to calculate the ` `// minimum cost ` `static` `int` `min_cost(String S)` `{ ` `    `  `    ``// Stores the minimum cost ` `    ``int` `cost = 0;`   `    ``// Stores the count of ` `    ``// characters found ` `    ``int` `F = 0;`   `    ``// Stores the count of ` `    ``// blank spaces found ` `    ``int` `B = 0;`   `    ``int` `count = 0;` `    `  `    ``foreach``(``char` `c ``in` `S.ToCharArray())` `        ``if``(c == ``' '``)` `           ``count++;` `           `  `    ``// Stores the count of ` `    ``// total characters` `    ``int` `n = S.Length - count; `   `    ``// If the count of characters ` `    ``// is equal to 1 ` `    ``if` `(n == 1) ` `        ``return` `cost;`   `    ``// Iterate over the string ` `    ``foreach``(``char` `inn ``in` `S.ToCharArray())` `    ``{ ` `        `  `        ``// Consider the previous character ` `        ``// together with current character ` `        ``if` `(inn != ``' '``)` `        ``{` `          `  `            ``// If not together already ` `            ``if` `(B != 0)` `            ``{` `                `  `                ``// Add the cost to group ` `                ``// them together ` `                ``cost += Math.Min(n - F, F) * B;` `                ``B = 0;` `            ``}` `            `  `            ``// Increase count of ` `            ``// characters found ` `            ``F += 1;` `        ``}` `        `  `        ``// Otherwise ` `        ``else` `        ``{ ` `            `  `            ``// Increase count of ` `            ``// spaces found ` `            ``B += 1;` `        ``} ` `    ``}` `    `  `    ``// Return the total ` `    ``// cost obtained ` `    ``return` `cost;` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{` `    ``String S = ``" @    \$"``;` `    `  `    ``Console.WriteLine(min_cost(S));` `}` `}`   `// This code is contributed by 29AjayKumar`

Output:

```4
```

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :