String Compression

Given a string of alphabets (from a to z), Print the count of the character appearing in the string right next to it. This is also called Run Length Encoding or String Compression.

Hash map approach

  1. In order to count the characters appearing in a string, create a map object that will store all the counts of variables.
  2. Iterate over the string and check if the current element is in the map. If not add it to the map and initialize it to 1. Otherwise, increment the count.
  3. Run a for loop on the created map object (called hash map), Print the count along with the key of the hash map.
  4. return the newly generated string.

Time Complexity

  • O(n) - Since we are iterating the array twice but separately.
Solve String Compression on Algochurn

Practice all the solutions below

Practice the most popular front-end questions asked in coding interviews with   Frontend Churn