Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2a6e17f

Browse files
Add medium problems
1 parent c2242cb commit 2a6e17f

File tree

2 files changed

+135
-0
lines changed

2 files changed

+135
-0
lines changed

‎Leetcode/medium/map-sum-pairs.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""
2+
# MAP SUM PAIRS
3+
4+
Implement the MapSum class:
5+
6+
MapSum() Initializes the MapSum object.
7+
void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
8+
int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.
9+
10+
Example 1:
11+
12+
Input
13+
["MapSum", "insert", "sum", "insert", "sum"]
14+
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
15+
Output
16+
[null, null, 3, null, 5]
17+
18+
Explanation
19+
MapSum mapSum = new MapSum();
20+
mapSum.insert("apple", 3);
21+
mapSum.sum("ap"); // return 3 (apple = 3)
22+
mapSum.insert("app", 2);
23+
mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5)
24+
25+
26+
Constraints:
27+
28+
1 <= key.length, prefix.length <= 50
29+
key and prefix consist of only lowercase English letters.
30+
1 <= val <= 1000
31+
At most 50 calls will be made to insert and sum.
32+
"""
33+
34+
class MapSum:
35+
36+
def __init__(self):
37+
"""
38+
Initialize your data structure here.
39+
"""
40+
self.root = {}
41+
self.endSymbol = "*"
42+
43+
def insert(self, key: str, val: int) -> None:
44+
current = self.root
45+
for letter in key:
46+
if letter not in current:
47+
current[letter] = {}
48+
current = current[letter]
49+
50+
current[self.endSymbol] = val
51+
52+
def sum(self, prefix: str) -> int:
53+
current = self.root
54+
for letter in prefix:
55+
if letter not in current:
56+
return 0
57+
current = current[letter]
58+
59+
return self.getSum(current)
60+
61+
def getSum(self, trieNode):
62+
currentSum = 0
63+
for letter in trieNode:
64+
if letter == self.endSymbol:
65+
currentSum += trieNode[letter]
66+
else:
67+
currentSum += self.getSum(trieNode[letter])
68+
69+
return currentSum
70+
71+
72+
# Your MapSum object will be instantiated and called as such:
73+
# obj = MapSum()
74+
# obj.insert(key,val)
75+
# param_2 = obj.sum(prefix)
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
# TOP K FREQUENT WORDS
3+
4+
Given a non-empty list of words, return the k most frequent elements.
5+
6+
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
7+
8+
Example 1:
9+
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
10+
Output: ["i", "love"]
11+
Explanation: "i" and "love" are the two most frequent words.
12+
Note that "i" comes before "love" due to a lower alphabetical order.
13+
Example 2:
14+
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
15+
Output: ["the", "is", "sunny", "day"]
16+
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
17+
with the number of occurrence being 4, 3, 2 and 1 respectively.
18+
Note:
19+
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
20+
Input words contain only lowercase letters.
21+
Follow up:
22+
Try to solve it in O(n log k) time and O(n) extra space.
23+
"""
24+
25+
class Solution:
26+
def topKFrequent(self, words: List[str], k: int) -> List[str]:
27+
frequency = {}
28+
trie = Trie()
29+
for word in words:
30+
freq = trie.insert(word)
31+
if freq == 1:
32+
frequency[word] = 1
33+
else:
34+
frequency[word] += 1
35+
36+
wordList = []
37+
for word in frequency:
38+
wordList.append((word, frequency[word]))
39+
40+
wordList.sort(key = lambda x: (-x[1], x[0]))
41+
return (word[0] for word in wordList[:k])
42+
43+
44+
class Trie:
45+
def __init__(self):
46+
self.root = {}
47+
self.endSymbol = "*"
48+
49+
def insert(self, word):
50+
current = self.root
51+
for letter in word:
52+
if letter not in current:
53+
current[letter] = {}
54+
current = current[letter]
55+
if self.endSymbol not in current:
56+
current[self.endSymbol] = 0
57+
58+
current[self.endSymbol] += 1
59+
return current[self.endSymbol]
60+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /