- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 56 lines of C++ from the credited upstream file 1409.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 4 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class FenwickTree {2 public:3 FenwickTree(int n) : sums(n + 1) {}4 5 void add(int i, int delta) {6 while (i < sums.size()) {7 sums[i] += delta;8 i += lowbit(i);9 }10 }11 12 int get(int i) const {13 int sum = 0;14 while (i > 0) {15 sum += sums[i];16 i -= lowbit(i);17 }18 return sum;19 }20 21 private:22 vector<int> sums;23 24 static inline int lowbit(int i) {25 return i & -i;26 }27};28 29class Solution {30 public:31 vector<int> processQueries(vector<int>& queries, int m) {32 vector<int> ans;33 34 FenwickTree tree(2 * m + 1);35 unordered_map<int, int> numToIndex;36 37 for (int num = 1; num <= m; ++num) {38 numToIndex[num] = num + m;39 tree.add(num + m, 1);40 }41 42 int nextEmptyIndex = m; 43 44 for (const int query : queries) {45 const int index = numToIndex[query];46 ans.push_back(tree.get(index - 1));47 48 tree.add(index, -1);49 tree.add(nextEmptyIndex, 1);50 numToIndex[query] = nextEmptyIndex--;51 }52 53 return ans;54 }55};56