0

screen shot of the errorI have written the following code to solve the Longest SubStrings With All Unique Characters. How can I fix this issue? , I understand what a null pointer exception is and why am I getting it , the question is what changes could be done such that I get the result based on the question. Again , what could be changed logically in this particular piece of code to make it work as its intended ,

receiving a null pointer exception

public class LongestSubStringWithAllUniqueChars {


static Map findUnique(char[] arr , int l , int r){
    Map<Character,Integer> map = new HashMap();
    for(int i=l;i<r;i++){
        if(map.containsKey(arr[l])){
            map.put(arr[l],map.get(arr[l])+1);
        }else{
            map.put(arr[l],1);
        }
    }
    map.forEach((c,v) ->{
        System.out.println(c+" "+v);
    });
    return map;
}
public static void main(String[] args) {
    String str = "GEEKSFORGEEKS";
    char[] arr = str.toCharArray();
    int l = 0;int r=0;
    int max =0;
    Map map  = new HashMap<>();


    while(r<arr.length){
        r++;
        map = findUnique(arr,l,r);
        if(map.size() < r-l+1){
            r++;
            map.put(arr[l],(int)map.get(arr[l])-1);
            while(map.size()< r-l+1){
                map.remove(arr[l],(int)map.get(arr[l])); // getting nullpointer here
                l++;
            }

        } else if(map.size()==r-l+1){
            max = r-l+1;
            r++;
        }
    }
    System.out.println(max);

}

}

  • Hi and welcome. I assume his is Java. When you get an exception in Java it should print the stacktrace indicating the line in your code that fails. If it doesn't do this, add a try/catch block around the code in your main() method and catch the NullPointerException and then in the catch, explicitly print the stacktrace (e.printStackTrace()). This will show exactly which row is failing. Edit your question to include the stacktrace (and add the Java tag). – DarkMatter Jan 02 '21 at 10:44

0 Answers0