Jobs
Interviews

Solve Selective String Compression using Python Language

Solve Selective String Compression using Python to enhance your skills with python coding practice , master coding concepts, and prepare for interviews with practical exercises and detailed solutions.

Selective String Compression

Difficulty : Medium

Categories :

  • Strings

Given a string s and an integer k, design a string compression algorithm that works as follows:

  • Group consecutive repeating characters
  • If a group's length is greater than k, compress it to: character + length
  • If a group's length is k or less, leave it uncompressed
  • Process the string from left to right

Return the compressed string.

Constraints:

  • 1 ≤ s.length ≤ 10^4
  • 1 ≤ k ≤ 100
  • s consists of lowercase English letters only

Examples:

Input: s = "aaabbbcccc", k = 2
Output: "aaa3c4"
Explanation:
'aaa' length=3 > k=2, compress to 'a3'
'bbb' length=3 > k=2, compress to 'b3'
'cccc' length=4 > k=2, compress to 'c4'
Input: s = "abbbccdddd", k = 3
Output: "abbbccd4"
Explanation:
'a' length=1 ≤ k=3, keep as 'a'
'bbb' length=3 ≤ k=3, keep as 'bbb'
'cc' length=2 ≤ k=3, keep as 'cc'
'dddd' length=4 > k=3, compress to 'd4'

Coding works best on a laptop or desktop, with a keyboard and a wider editor. You can read the problem here and solve it there.

Problem Solving

Input

What You'll Find Here

Interactive Exercises Practice coding with problems designed for beginners and experts.

Step-by-Step Solutions Understand every step of the solution process.

Real-World Scenarios Apply your skills to real-world problems and boost your confidence.

Choose from the following categories