467. Minimum and Maximum Count Data Structure
Minimum and Maximum Count Data Structure

Implement AllOne to maintain counts for string keys and retrieve a key with the smallest or largest count. Each method must run in O(1) average time.

Constructor and Methods

public AllOne()
  • Creates an empty data structure.
public void inc(String key)
  • key: Increase its count by 1. If absent, insert it with count 1.
public void dec(String key)
  • key: Decrease its count by 1. Remove it when its count becomes 0.
public String getMaxKey()
  • Returns a key with the largest count, or "" if the structure is empty.
public String getMinKey()
  • Returns a key with the smallest count, or "" if the structure is empty.

Tie Rule

If multiple keys share the requested count, return the key that reached that count earliest. Leaving and later returning to a count resets this order. Getter calls do not change the order.

Constraints

  • 1 ≤ key.length() ≤ 10.
  • key contains only lowercase English letters.
  • The key passed to dec always exists.
  • At most 50,000 calls to inc, dec, getMaxKey, and getMinKey combined.

Examples

Parameter names in example calls are shown for readability and are not Java syntax. Calls to inc and dec return no value.

Example 1: Updates and Ties

  1. AllOne counts = new AllOne()
  2. counts.inc(key = "plum")
  3. counts.inc(key = "kiwi")
  4. counts.getMaxKey() returns "plum".
  5. counts.inc(key = "kiwi")
  6. counts.getMaxKey() returns "kiwi".
  7. counts.getMinKey() returns "plum".
  8. counts.inc(key = "plum")
  9. counts.getMinKey() returns "kiwi".
  10. counts.dec(key = "plum")
  11. counts.getMinKey() returns "plum".
  12. counts.dec(key = "kiwi")
  13. counts.getMaxKey() returns "plum".

When both counts become 2, "kiwi" wins the tie. After both decrease to 1, "plum" wins because it returned to that count first.

Example 2: Removal and Reinsertion

  1. AllOne counts = new AllOne()
  2. counts.getMinKey() returns "".
  3. counts.inc(key = "oak")
  4. counts.dec(key = "oak")
  5. counts.getMaxKey() returns "".
  6. counts.inc(key = "elm")
  7. counts.inc(key = "oak")
  8. counts.getMinKey() returns "elm".
  9. counts.getMaxKey() returns "elm".
  10. counts.dec(key = "elm")
  11. counts.dec(key = "oak")
  12. counts.getMinKey() returns "".

A removed key starts again at count 1 when reinserted. The earlier "oak" insertion does not affect the tie with "elm".



Please use Laptop/Desktop or any other large screen to add/edit code.