Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 432 · Advanced / Mixed

All O`one Data Structure

LeetCode 432 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

count map + count → keys buckets.

ಕಠಿಣHash TableLinked ListDesignDoubly-Linked List
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು All O`one Data Structure (LeetCode 432) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Advanced / Mixed ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Keep each key's count, and a map from count to the set of keys with that count. Incrementing or decrementing moves a key between buckets; the min and max keys come from the smallest and largest non-empty bucket.

Approach

  1. 1

    inc: move the key from bucket c to c+1.

  2. 2

    dec: move it to c−1, or forget it at 1.

  3. 3

    Delete empty buckets.

  4. 4

    getMax/getMin: any key from the max/min bucket.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Count bucketsPythonnear-O(1) per op
class AllOne:

    def __init__(self):
        self.freq=defaultdict(set)
        self.count=defaultdict(int)

    def inc(self, key: str) -> None:
        count = self.count[key]
        if count>0:
            self.freq[count].remove(key)
        self.count[key]+=1
        self.freq[count+1].add(key)
        if not self.freq[count]:
            del self.freq[count]

    def dec(self, key: str) -> None:
        count=self.count[key]
        self.freq[count].remove(key)
        if count==1:
            del self.count[key]
        else:
            self.count[key]-=1
            self.freq[count-1].add(key)
        if not self.freq[count]:
            del self.freq[count]
    def getMaxKey(self) -> str:
       return next(iter(self.freq[max(self.freq)])) if self.freq else ""

    def getMinKey(self) -> str:
        return next(iter(self.freq[min(self.freq)])) if self.freq else ""


# Your AllOne object will be instantiated and called as such:
# obj = AllOne()
# obj.inc(key)
# obj.dec(key)
# param_3 = obj.getMaxKey()
# param_4 = obj.getMinKey()
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

All O`one Data Structure — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

All O`one Data Structure ಹಿಂದಿನ intuition ಏನು?

Keep each key's count, and a map from count to the set of keys with that count. Incrementing or decrementing moves a key between buckets; the min and max keys come from the smallest and largest non-empty bucket.

All O`one Data Structure (LeetCode 432) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. inc: move the key from bucket c to c+1. 2. dec: move it to c−1, or forget it at 1. 3. Delete empty buckets. 4. getMax/getMin: any key from the max/min bucket.

All O`one Data Structure ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(1) inc/dec, O(#buckets) for max/min here. Space: O(n). (Accepted approach: Count buckets.)

All O`one Data Structure ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

max()/min() over bucket keys isn't O(1) — a doubly linked list of buckets makes every operation O(1).