mediumHashingPattern: Hash Map / Dynamic Array
Randomized Set Operations Solution
Problem Statement
You are given a sequence of operations where each operation is either an insertion or a deletion. Implement a data structure that supports these operations and calculates the total value after all operations are performed. The operations are represented as a string where '1 val' indicates an insertion of value val and '2 val' indicates a deletion of value val.
Examples
Example 1:
Input:["1 10","1 20","2 15","1 30","2 25"]
Output:45
Explanation: Buy at 10, buy at 20, sell at 15 (one stock), buy at 30, sell at 25 (one stock), the portfolio has 10, 20, and 30 - 15 - 25 = 10
Constraints
- 1 <= ops <= 10^5
- -10^9 <= val <= 10^9
Time: O(1) Space: O(N)
HashMap + Array. To remove element E at index I, swap E with last element in array. Update last element's index in HashMap to I. Pop from array and remove E from map. Time O(1).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
