Intuition
Solution becomes simpler if you divide the reading pointer and writing pointer
- loop through chars and do another loop inside to count number of occurrence of char
- write the letter to write pointer
- write each digits of count and increment write pointer accordingly if count is greater than 1
Optimal Solution
class Solution:
def compress(self, chars: List[str]) -> int:
i = write = 0
while i < len(chars):
curr = chars[i]
count = 0
while i < len(chars) and chars[i] == curr:
i += 1
count += 1
chars[write] = curr
write += 1
if count > 1:
for digit in str(count):
chars[write] = digit
write += 1
return write
Time Complexity
Time Complexity O(N)
Space Complexity O(1)