Candy

Intuition My thought was first going left to right checking both neighbours. For example, for [1,2,3,4] would work perfectly. However it’s not possible to solve this in one pass checking both neighbours. We need to use a two pass approach, LTR, RTL. To visualize better the problem, using [1,2,3,4] let’s see how many candies LTR and RTL would give for each children: LTR [1,2,3,4] -> [1,2,3,4] since it's always increase each children get's one more candy than the previous one. RTL [1,2,3,4] -> [1,1,1,1] From RTL perspective, it's always decreasing, so all children get's one. In this case the correct solution is [1,2,3,4] ...

April 20, 2025 · 2 min

Trapping rain water

Intuition This problem uses a very similar solution to 135. Candy. Important point to notice is: water can’t be at the edges, the edge is either 0 heigh (water leak) or wall with no water on top. So with this in mind we can ignore water on edges. The volume of water in any place is water = max_height - current_height. Let’s take this example [0,2,0,3,0,2], the # represents the walls, the . represents the water. ...

April 20, 2025 · 2 min

Is Subsequence

Intuition Another way to read the problem is: find if all s characters are present in t, in the same order. It doesn’t have to be consecutive. We need to keep two pointers: One for the string t One for the string s We got loop through the string t, and if t[tPointer] == s[iPointer], we increase both. If t[tPointer] != s[iPointer], will increase just tPointer. At the end if iPointer==len(s) we reach end of s, we are good, return True This will be solved in time O(n) and space(1), since is one pass and we don’t use additional structures other than the pointers. ...

April 19, 2025 · 2 min

Product of array except self

Intuition Brute force, but it doesn’t work. Approach I had to read the solution. The key is math, the order of a product operation do not affect the final result. Visualization makes it easier. A*B*C*D = (A*B)*(C*D) Let’s see one example in action. Consider the following array n=[2,2,3,2,2] When calculating the answer for n[2], we are calculating the product of two separated grous (2*2) * (2*2), left L and right R independently. ...

April 19, 2025 · 2 min

Gas Station

Intuition Find the first station where we have a net positive tank. However that solution is not optimized. Approach After reading the editorial, it’s possible to complete the solution with optimal time complexity using the greedy approach (one pass). The idea is to go iterate over the elements and whenever we find a net negative level we restart the segment and keep the next array index as starting index. Also, while going over the elements we need to keep a the final tank level. If the final tank level is negative, then there’s no solution. ...

April 17, 2025 · 1 min