Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# n: total # of elements in strs.
# k: maximum length of a string in strs.
# Time complexity: O(nlog(n))
# Space complexity: O(n).
ans = collections.defaultdict(list)
for word in strs:
ans[tuple(sorted(word))].append(word)
return ans.values()
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# n: total # of elements in strs.
# k: maximum length of a string in strs.
# Time complexity: O(n).
# Space complexity: O(n).
ans = collections.defaultdict(list)
for word in strs:
count = [0]*26
for char in word:
count[ord(char) - ord('a')] += 1
ans[tuple(count)].append(word)
return ans.values()
https://leetcode.com/problems/find-k-closest-elements/ Naive def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: L = sorted([(abs(elt - x), elt) for elt in arr], key=lambda tup: tup[0]) return sorted([tup[1] for tup in L[:k]]) Opti
Sep 23, 2022Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack();
Jun 27, 2022Given a string containing just the characters $($, $)$, ${$, $}$, $[$ and $]$, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1:
Jun 27, 2022Solution 1 Time complexity: O(n³) Space complexity: O(n) class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n < 3: return []
Apr 23, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up