Posts

Showing posts from May, 2024

StringBuilder III

Image
Another example where string concatenation leads to TLE while the StringBuilder approach gets to the expected solution. A lot of concatenations using Strings in C# will lead to many objects being created all the time, which not only wastes memory but also time in the process (including GC). This article from SO discusses this theme well:  c# - benefits of using a stringbuilder - Stack Overflow Code is down below, cheers, ACC String Compression III - LeetCode 3163. String Compression III Medium 45 3 Add to List Share Given a string  word , compress it using the following algorithm: Begin with an empty string  comp . While  word  is  not  empty, use the following operation: Remove a maximum length prefix of  word  made of a  single character   c  repeating  at most  9 times. Append the length of the prefix followed by  c  to  comp . Return the string  comp .   Example 1: Input:   word ...

Linearity based on bucketization

Image
Common problems require a bucketization strategy in order to speed up the solution. It is a tradeoff between space and time. The problem below would naively require an N^2 approach. In order to speed it up, here is the approach: 1. Count the number of digits from 0..9 in each position of the number. Notice that there are 5 positions available (since the max number is 10^5). 2. At this point, for each position, do a nested loop (0..9, nested with 0..9) multiplying the ones that are different, and adding them to the result (use a long cast to avoid overflow) The first step takes N. The second is quicker: 5*10*10 = 500, or constant time. Works relatively fast. Code is down below. If you want to try some copilot, do it too, but the ones that I tried provided the wrong answer. Cheers, ACC. Sum of Digit Differences of All Pairs - LeetCode 3153. Sum of Digit Differences of All Pairs Medium 62 4 Add to List Share You are given an array  nums  consisting of  positive  in...