0

Here is my code, being ran on LeetCode:

class Solution {
    private int[] nums;
    private HashMap<Integer, Integer> memo = new HashMap<Integer, Integer>();
    private HashMap<Integer, Integer> occurances = new HashMap<Integer, Integer>();
    private int dp(int current) {
        //System.out.println(current);
        return 0;
    }
    
    public int deleteAndEarn(int[] nums) {
        for(var i = 0; i < nums.length; i++) {
            var n = nums[i];
            var o = occurances.getOrDefault(n, 0);
            o++;
            occurances.put(n, o);
        }
        
        int max = 0;
        for(Integer i: occurances.keySet()) {
            System.out.println(i);
            max = Math.max(dp(i), max);
        }
        
        return max;
    }
}

and here is the stdout:

2
3
4
5
9

where nums = '[3,4,2,9,2,4,3,2,4,5]'

I have tried multiple combinations of nums and it is always ordered. As far as I understand HashMap put and HashMap keySet are both constant time operations and not n log(n). So what is happening under the hood that is causing to always be sorted? Is it safe to assume the time complexity of my simple algorithm of printing numbers is still o(n)? Is it safe to assume at some point these will stop being ordered?

Gregory Ray
  • 305
  • 2
  • 4
  • 2
    It's coincidental and related to the Integer hashCode calculation. Change your `HashMap` to `HashMap occurrences = new HashMap<>(2, 3.0f);` and see the difference. – WJS Jul 16 '23 at 22:03
  • Try some variations; for example, maybe keys 7 and 17 (in a default-capacity hashmap) – Arfur Narf Jul 16 '23 at 22:11

0 Answers0