- 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 Java from the credited upstream file 1409.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 FenwickTree(int n) {3 sums = new int[n + 1];4 }5 6 public void add(int i, int delta) {7 while (i < sums.length) {8 sums[i] += delta;9 i += lowbit(i);10 }11 }12 13 public int get(int i) {14 int sum = 0;15 while (i > 0) {16 sum += sums[i];17 i -= lowbit(i);18 }19 return sum;20 }21 22 private int[] sums;23 24 private static int lowbit(int i) {25 return i & -i;26 }27}28 29class Solution {30 public int[] processQueries(int[] queries, int m) {31 int[] ans = new int[queries.length];32 33 FenwickTree tree = new FenwickTree(2 * m + 1);34 Map<Integer, Integer> numToIndex = new HashMap<>();35 36 for (int num = 1; num <= m; ++num) {37 numToIndex.put(num, num + m);38 tree.add(num + m, 1);39 }40 41 int nextEmptyIndex = m; 42 43 for (int i = 0; i < queries.length; ++i) {44 final int query = queries[i];45 final int index = numToIndex.get(query);46 ans[i] = tree.get(index - 1);47 48 tree.add(index, -1);49 tree.add(nextEmptyIndex, 1);50 numToIndex.put(query, nextEmptyIndex--);51 }52 53 return ans;54 }55}56