Tutorialspoint
Problem
Solution
Submissions

String Compression Algorithm

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to implement a basic string compression algorithm. The algorithm should replace consecutive repeated characters with the character followed by the count of repetitions. If the compressed string is not smaller than the original string, return the original string.

Example 1
  • Input: s = "aabcccccaaa"
  • Output: "a2b1c5a3"
  • Explanation:
    • "aa" becomes "a2"
    • "b" becomes "b1"
    • "ccccc" becomes "c5"
    • "aaa" becomes "a3"
Example 2
  • Input: s = "ab"
  • Output: "ab"
  • Explanation:
    • "a" becomes "a1" and "b" becomes "b1"
    • The compressed string "a1b1" is longer than the original string "ab"
    • So we return the original string.
Constraints
  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters only
  • Time Complexity: O(n), where n is the length of the string
  • Space Complexity: O(n)
StringsDeloitteApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Iterate through the string and count consecutive characters.
  • Build the compressed string using a StringBuilder for efficiency.
  • Compare the length of the compressed string with the original.
  • Handle edge cases like empty strings or strings with no compression.

Steps to solve by this approach:

 Step 1: Handle edge cases - return the original string if it's empty or has only one character.
 Step 2: Initialize a StringBuilder to build the compressed string efficiently.
 Step 3: Set the first character as the current character and initialize a counter to 1.
 Step 4: Iterate through the string from the second character, incrementing the counter if the current character matches the previous one.
 Step 5: When a different character is encountered, append the previous character and its count to the StringBuilder, then reset the counter and update the current character.
 Step 6: After the loop, append the last character and its count to the StringBuilder.
 Step 7: Compare the length of the compressed string with the original string and return the shorter one.

Submitted Code :