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 |
Input: str = ” @ $”
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 ”
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:
- Initialize the total cost with 0.
- Transverse the string and count the spaces between the two characters.
- Get both the characters together and add the cost to the total cost.
- Repeat the above steps for all characters.
Below is the implementation of the above approach:
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.
- Cost of rearranging the array such that no element exceeds the sum of its adjacent elements
- Remove spaces from a given string
- Remove extra spaces from a string
- C++ Program to remove spaces from a string
- How to remove all white spaces from a String in Java?
- Largest palindromic string possible from given strings by rearranging the characters
- String containing first letter of every word in a given string with spaces
- Make palindromic string non-palindromic by rearranging its letters
- Maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1
- Minimum Cost of deletions such that string does not contains same consecutive characters
- Minimum cost of flipping characters required to convert Binary String to 0s only
- Removing spaces from a string using Stringstream
- Move spaces to front of string in single traversal
- C program to trim leading white spaces from String
- URLify a given string (Replace spaces is %20)
- Python code to move spaces to front of string in single traversal
- Put spaces between words starting with capital letters
- Regex in Python to put spaces between words starting with capital letters
- Smallest number by rearranging digits of a given number
- Largest number not greater than N which can become prime after rearranging its digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.