one of the best explanations for this problem!! i was having so much trouble with this specific question and after listening closely to your explanation and seeing your code, it became so much more clear. thank you! thank you! thank you!!!!!
Solution Without Pointers: class Solution: def compress(self, chars: List[str]) -> int:
# Initialize an empty list to store the result result = [] n = len(chars) i = 0 while i < n: char = chars[i] count = 0 # Count the number of occurrences of the current character while i < n and chars[i] == char: count += 1 i += 1 # Append the character to the result result.append(char) # If count is greater than 1, append the digits of the count if count > 1: result.extend(list(str(count))) # Overwrite the original chars array with the result chars[:] = result # Return the new length of the chars array return len(result)
Thanks for this , I was able to solve string compression 3 in similar way, but later only when I tried out this problem I got stuck at appending the count part. 👌👌
The problem has a constraint that you must only use constant extra space. Using a hashmap would violate this constraint as that would be O(n) extra space.
Wow, perfect timing. I'm currently solving the Leetcode 75 and exactly today I arrived to this problem. Great explanation. Thank you!
one of the best explanations for this problem!! i was having so much trouble with this specific question and after listening closely to your explanation and seeing your code, it became so much more clear. thank you! thank you! thank you!!!!!
Wonderful videos Deepti !
Solution Without Pointers:
class Solution:
def compress(self, chars: List[str]) -> int:
# Initialize an empty list to store the result
result = []
n = len(chars)
i = 0
while i < n:
char = chars[i]
count = 0
# Count the number of occurrences of the current character
while i < n and chars[i] == char:
count += 1
i += 1
# Append the character to the result
result.append(char)
# If count is greater than 1, append the digits of the count
if count > 1:
result.extend(list(str(count)))
# Overwrite the original chars array with the result
chars[:] = result
# Return the new length of the chars array
return len(result)
Thanks for this , I was able to solve string compression 3 in similar way, but later only when I tried out this problem I got stuck at appending the count part. 👌👌
why chars[insert] = chars[i], when i and insert both equal to 0 at the beginning of the answer?
You are smart + beautiful
Hey dipti !! just a thought for this problem if we use a hash map it would be easy right?
The problem has a constraint that you must only use constant extra space. Using a hashmap would violate this constraint as that would be O(n) extra space.
@@vikkalkat4523oh ! Got it thanks