Add Python implementations for LeetCode 155 and 705#2629
Add Python implementations for LeetCode 155 and 705#2629rishigoswamy wants to merge 1 commit intosuper30admin:masterfrom
Conversation
|
Strengths:
Areas for Improvement:
Suggested Improvements:
Example of improved code for def add(self, key: int) -> None:
primary = key % self.primaryArraySize
secondary = key // self.primaryArraySize
if self.table[primary] is None:
# Initialize the secondary array only when needed
self.table[primary] = [False] * self.secondaryArraySize
self.table[primary][secondary] = TrueBut note: in the current student code, the entire table is pre-allocated with lists of booleans. So to implement lazy initialization, you should initialize Also, for the key 0, the secondary index is 0. For key 1000000, primary=0 and secondary=1000. So you need to ensure the secondary array for primary=0 has size 1001 (to include index 1000). For other primary buckets, the maximum secondary index is 999 (for key 999999: primary=999, secondary=999). So you can allocate size 1000 for primary buckets 1 to 999, and size 1001 for primary bucket 0. This is handled in the reference solution. Overall, the student's solution is correct and efficient in time, but could be improved in memory usage. |
|
Your solution is well thought out and correctly implements the HashSet operations with constant time complexity. The two-level hashing approach is appropriate for the problem constraints. One area for improvement is space efficiency. Currently, you allocate the entire 2D array upfront, which uses about 1 million boolean values (each boolean is typically 1 byte, so about 1 MB). This is acceptable given the constraints (key range up to 10^6 and at most 10^4 operations), but it could be optimized. The reference solution uses lazy initialization: it only creates the secondary arrays when a key in that primary bucket is added for the first time. This reduces the space usage when the number of keys is small. For example, in the reference solution:
You could consider modifying your solution to use lazy initialization to save space. However, your current solution is correct and efficient enough for the problem constraints. Another minor point: in the def add(self, key: int) -> None:
primaryKey, secondaryKey = self.hashKeys(key)
# ... rest of the codeOverall, your solution is correct and efficient. Well done! |
No description provided.