LC 443: String Compression
Solved using HashMap and Two Pointers.:: ON THIS PAGE 3
The problem asks us to compress a list of characters in-place and return the new length. Since we need to modify the array while reading it, a Two Pointer approach is perfect. One pointer (read_index) reads through the original characters to find groups, and another pointer (write_index) keeps track of where we are writing the compressed result.
Approach
- Initialize two pointers:
read_index: used to iterate through the array and counting consecutive characters.write_index: used to overwritecharswith our compressed results.
- Iterate through the array
while read_index < len(chars). - Inside the loop, we identify the current character (
ch) and count its consecutive occurrences using an innerwhileloop. - Once we have the count:
- We write the character
chto thewrite_indexposition. - If the count is greater than 1, we convert the count to a string and write each digit to the
charsarray, incrementingwrite_indexas we go.
- We write the character
- Finally, we return
write_index, which represents the new length of the compressed array.
Example Trace: Chars = ["a", "a", "B", "B", "C"]
- Start Pointers read_index (
R) and write_index (W) start at the beginning.
- Process Group
a. We find twoas. We writeaand2.
- Process Group
bWe find twobs. We writeband2.
- Process Group
cWe find onec. We writec. (no number needed)
)
Code
return 0
= 0
= 0
=
=
= 0
+= 1
+= 1
=
+= 1
=
+= 1
return
Complexity
Time complexity: $O(N)$
We iterate through thecharsarray exactly once.Space complexity: $O(1)$
We perform the compression in-place.
> finding connected notes…
> 4 notes share a tag
207-course-schedule.md LC 207: Course Schedule 210-course-schedule-2.md LC 210: Course Schedule II 295-median-from-data-stream.md LC 295: Find Median from Data Stream 01-two-sum.md LC 001: Two Sum