java solution and why we need to initialize map to 0 at index -1


  • 0
    M

    This is an extension to this graphic solution

    public class Solution {
     public int findMaxLength(int[] nums) {
        int max = 0;
        int countDiff = 0;
        
        Map<Integer, Integer> indexBySum = new HashMap<>();
        // Needs to be initialized to index -1 for correct calculations of the countDiff being 0.
        // Either initialize it to 0, -1 or if you initialize it to 0, 0 then you need to handle the case when countDiff == 0 then max will be simply i+1.
        indexBySum.put(0,-1);
        //indexBySum.put(0,0);
        
        for(int i = 0; i < nums.length; ++i){
            countDiff += nums[i] == 0 ? -1 : 1;
            // This commented out code would be needed it we initialized map with (0, 0) 
            // if(countDiff == 0){
            //     max = i+1;
            // }
            /*else*/
            if(indexBySum.containsKey(countDiff)){
                max = Math.max(max, i - indexBySum.get(countDiff));
            }else{
                indexBySum.put(countDiff, i);
            }
        }
        
        return max;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.