-3

When i'm trying leetcode problem 76, at one point I am trying to get a value paired to key in one of the two maps (smap) for that I have used smap.get(curr)(as you can see in the last if condotion), but I am getting an error like this

java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.HashMap.get(Object)" is null

at line 39, Solution.minWindow

at line 54, DriverSolution.helper

at line 87, Driver.main

but when I use smap.getOrDefault(curr,0) it's working fine without giving any error

Can anyone explain why the error is occurring? Below is the link to the Leetcode problem 76.

class Solution {
    public String minWindow(String s, String t) {
        String ans="";
        int min_window=Integer.MAX_VALUE,count=0,n=t.length(),window_start=0;
       
        HashMap<Character,Integer>smap=new HashMap();
        
        HashMap<Character,Integer>tmap=new HashMap();
        
        for(char c:t.toCharArray()){
            tmap.put(c,tmap.getOrDefault(c,0)+1);
        }
        
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            smap.put(c,smap.getOrDefault(c,0)+1);
            
            if(tmap.containsKey(c) && smap.get(c)<=tmap.get(c)){
                count++;
            }
            
            while(count==n){
                if(min_window>i-window_start+1){
                    min_window=i-window_start+1;
                    ans=s.substring(window_start,i+1);
                }
                
                char curr=s.charAt(window_start);
                
                if(smap.get(curr)==1){
                    smap.remove(curr);
                }
                else{
                    smap.put(curr,smap.get(curr)-1);
                }
                
                window_start++;
                
                if(tmap.containsKey(curr) && smap.get(curr)<tmap.get(curr)){
                    count--;
                }
            }
        }
        return ans;
    }
}
Abhi Ram
  • 1
  • 1
  • 1
    You don't check if the key `curr` is in `smap` before getting it, therefore the comparison fails when `smap.get(curr)` returns null. Same NPE will happen in the `else` case `smap.get(curr)-1` - I would also highly suggest you to look at the methods of Map such as`putIfAbsent` and `computeIfPresent` to avoid code like `smap.put(c,smap.getOrDefault(c,0)+1)` – thinkgruen May 16 '22 at 12:41
  • An aside: your declarations should be like `Map smap = new HashMap<>();` in idiomatic Java. – David Conrad May 16 '22 at 13:33

0 Answers0