- 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
- 59 lines of Java from the credited upstream file 3321.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 3 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 Solution {2 3 public long[] findXSum(int[] nums, int k, int x) {4 long[] ans = new long[nums.length - k + 1];5 Map<Integer, Integer> count = new HashMap<>();6 TreeSet<Pair<Integer, Integer>> top =7 new TreeSet<>(Comparator.comparingInt(Pair<Integer, Integer>::getKey)8 .thenComparingInt(Pair<Integer, Integer>::getValue));9 TreeSet<Pair<Integer, Integer>> bot =10 new TreeSet<>(Comparator.comparingInt(Pair<Integer, Integer>::getKey)11 .thenComparingInt(Pair<Integer, Integer>::getValue));12 13 for (int i = 0; i < nums.length; ++i) {14 update(nums[i], 1, count, top, bot);15 if (i >= k)16 update(nums[i - k], -1, count, top, bot);17 18 while (!bot.isEmpty() && top.size() < x) {19 Pair<Integer, Integer> pair = bot.pollLast();20 top.add(pair);21 windowSum += (long) pair.getValue() * pair.getKey();22 }23 24 while (!bot.isEmpty() && (bot.last().getKey() > top.first().getKey() ||25 bot.last().getKey().equals(top.first().getKey()) &&26 bot.last().getValue() > top.first().getValue())) {27 Pair<Integer, Integer> pairB = bot.pollLast();28 Pair<Integer, Integer> pairT = top.pollFirst();29 top.add(pairB);30 bot.add(pairT);31 windowSum += (long) pairB.getValue() * pairB.getKey();32 windowSum -= (long) pairT.getValue() * pairT.getKey();33 }34 if (i >= k - 1)35 ans[i - k + 1] = windowSum;36 }37 return ans;38 }39 40 private long windowSum = 0;41 42 43 private void update(int num, int freq, Map<Integer, Integer> count,44 TreeSet<Pair<Integer, Integer>> top, TreeSet<Pair<Integer, Integer>> bot) {45 if (count.getOrDefault(num, 0) > 0) { 46 Pair<Integer, Integer> pair = new Pair<>(count.get(num), num);47 if (bot.remove(pair)) {48 49 } else {50 top.remove(pair);51 windowSum -= (long) num * count.get(num);52 }53 }54 count.merge(num, freq, Integer::sum);55 if (count.get(num) > 0)56 bot.add(new Pair<>(count.get(num), num));57 }58}59