 /// A collection that associates keys with one or more values.
 @_spi(Testing) public struct Multidictionary<Key: Hashable, Value: Hashable>: Collection, Equatable {
   private var dictionary: Dictionary<Key, Set<Value>> = [:]
+
+  /// Reverse index used to make value removal more efficient.
+  private var reverseIndex: Dictionary<Value, Set<Key>> = [:]
   
   public typealias Element = (Key, Set<Value>)
   public typealias Index = Dictionary<Key, Set<Value>>.Index

  /// - Returns: The removed element, if any.
  @discardableResult
  public mutating func removeValue(_ v: Value, forKey key: Key) -> Value? {
    return self.dictionary[key, default: []].remove(v)
  }


  ///
  /// - Parameter v: The value to remove.
  public mutating func removeOccurrences(of v: Value) {
    for k in self.reverseIndex[v, default: []] {
      self.dictionary[k]!.remove(v)
    }
    self.reverseIndex.removeValue(forKey: v)
  }
}
