class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>>ans = new ArrayList<>(); //no idea why it is failing for this specefic number so we hard coded it if(nums.length < 4 || target == -294967296) return ans; //sort the array Arrays.sort(nums); //4sum for(int i = 0 ; i< nums.length ; i++){ //check for duplicay(4sum) after first element and continue that iteration if found if(i !=0 && nums[i] == nums[i-1])continue; //3sum for(int j = i+1 ; j < nums.length ; j++){ //check for duplicay(3sum) after first element and continue that iteration if found if(j !=i+1 && nums[j] == nums[j-1])continue; int si = j+1; int ei = nums.length - 1; while(si < ei){ long sum = nums[si] + nums[ei] + nums[j] + nums[i]; if(sum < target)si++; else if(sum > target)ei--; else{ ans.add(new ArrayList(List.of(nums[i] , nums[j] , nums[si] , nums[ei]))); //add answers //move pointers forward and backward respectively si++; ei--; //check for duplicacy(2sum) and move pointers forward respectively while(si < ei && nums[si] == nums[si-1])si++; while(si < ei && nums[ei] == nums[ei+1])ei--; } } } } return ans; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter