Valid Parentheses

Intuition Recursive approach won’t work, it’s too expensive. Approach Use a stack to keep track of the opening brackets. Whenever we see a closing bracket, we check if the top of the stack has the corresponding closing one. When we see a closing bracket we will return False if the stack: Does not have any element The top of the stack does not match with the closing bracker After going through all character, if there’s any element left in the stack, we also return False. ...

May 2, 2025 · 1 min

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

Valid Anagram

Intuition Count frequency of each Approach Create a map conting the frequency of one string. For the second string decrease by one each letter: If the count of a given letter is < 0, returns false If the letter does not yet exists in the map, returns false Complexity Time complexity: O(n) Space complexity: O(n) Code class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) != len(t): return False letters = {} for c in s: if c in letters: letters[c] += 1 else: letters[c] = 1 for c in t: if c in letters: letters[c] -= 1 if letters[c] < 0: return False else: return False return sum(letters.values()) == 0 But there’s a even shorter version: ...

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