Group Anagrams

Intuition Create a map os strings, group by it’s sorted version. Approach Create a map os strings, group by it’s sorted version. Complexity Time complexity: O(n logn) Space complexity: O(n) Code class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ _map = {} for s in strs: _sorted = "".join(sorted(s)) if _sorted in _map: _map[_sorted].append(s) else: _map[_sorted] = [s] return _map.values()

April 29, 2025 · 1 min

Container With Most Water

Intuition Use two pointers, starting at the edges. Approach Use two pointer, starting at the edge. Always move the pointer with less height Complexity Time complexity: O(n) Space complexity: O(1) Code print(1)class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ start = 0 end = len(height)-1 maxVolume = -1 while start<end: h = min(height[start], height[end]) maxVolume = max(maxVolume, (end - start) * h) if height[start] < height[end]: start += 1 else: end -= 1 return maxVolume

April 24, 2025 · 1 min

Two Sum II - Input Array Is Sorted

Intuition Keep a map of the numbers, and lookup for it’s complement based on target. Approach Loop through all elements, check if the complement of the current number is already in the store. In case it’s true, return current index and the index stored. in case it’s not, add the current number to the store. The key here is to store the current number in the map, not the complement ...

April 22, 2025 · 1 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