String Compression
Updated
Problem statement
Given a string chars, return its compressed form.
A run is a longest block of equal characters standing next to each other. Going from left to right, replace each run with its character followed by the length of the run, written in decimal. A run of length 1 is written as the character alone, with no count. A count can have more than one digit, so twelve z characters in a row become z12.
Two runs of the same character that are not next to each other are written separately. Return the compressed form even when it is not shorter than chars.
Function
compress(chars: String) → StringExamples
Example 1
chars = "qqqquuuaaaaabb"return = "q4u3a5b2"The string splits into four runs: qqqq, uuu, aaaaa and bb, with lengths 4, 3, 5 and 2. Each run becomes its letter followed by its length, which gives q4u3a5b2.
Example 2
chars = "aabccca"return = "a2bc3a"The runs are aa, b, ccc and a. The single b and the single a at the end are written with no count. The two runs of a are not next to each other, so they stay separate: the answer is a2bc3a, not a3bc3.
Example 3
chars = "zzzzzzzzzzzz"return = "z12"All twelve characters form one run of length 12, so the answer is the letter followed by both digits: z12.
Constraints
1 <= chars.length <= 10^4charsconsists of lowercase English letters only.
More Shnoor International Onsite Interview questions
Similar questions at other companies
- Longest Spoken PrefixElevenLabs · ONSITE INTERVIEWElevenLabs interview questions
- Palindrome Check Ignoring SymbolsWalmart · ONSITE INTERVIEWWalmart interview questions
- Reverse a String Keeping Dashes in PlaceNykaa · ONSITE INTERVIEWNykaa interview questions
- Reverse Vowels of a StringGoogle · ONSITE INTERVIEWGoogle interview questions
- Valid Palindrome After NormalizationKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Count Binary SubstringsDocuSign · ONSITE INTERVIEWDocuSign interview questions
- Minimum Changes for Palindromic BlocksCitadel · OA · PHONE SCREEN · ONSITE INTERVIEWCitadel interview questions
- Palindrome Match PercentageApple · ONSITE INTERVIEWApple interview questions
- Reverse A StringNVIDIA · ONSITE INTERVIEWNVIDIA interview questions
- Validate a Word AbbreviationSalesforce · ONSITE INTERVIEWSalesforce interview questions