Q43 PepCoding | Pairs With Given Sum In Two Sorted Matrices

PHOTO EMBED

Mon Jan 30 2023 06:05:03 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

import java.util.*;

public class Main {
	
    public static int solve(int[][] nums1, int[][] nums2, int tar) {
		int ans =0;
		//add first array in hashmap and make its frequency map
		HashMap<Integer,Integer> fmap = new HashMap<>();
		
		for(int i=0 ; i< nums1.length ; i++){
		    for(int j = 0 ; j < nums1[0].length ; j++){
		        
		        int val = nums1[i][j];
		        
		        fmap.put(val , fmap.getOrDefault(val,0)+1);
		    }    
		    
		}
		
		
//now iterate through 2nd array and if target - nums2[i] is present in map then add its frequency (as frequency will be no. pair which is equal to target)

		for(int i =0 ; i<nums2.length ; i++){
		   for(int j = 0 ; j < nums2[0].length ; j++){
		       
		    int val = nums2[i][j];
		    int rem = tar - val;    //remaining value
		    
		    if(fmap.containsKey(rem))
		        ans += fmap.get(rem);
		   }
		}
		
		return ans;
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int[][] mat1 = new int[N][N];
		for (int i = 0; i < mat1.length; i++) {
			for (int j = 0; j < mat1[0].length; j++) {
				mat1[i][j] = sc.nextInt();
			}
		}

		int[][] mat2 = new int[N][N];
		for (int i = 0; i < mat2.length; i++) {
			for (int j = 0; j < mat2[0].length; j++) {
				mat2[i][j] = sc.nextInt();
			}
		}
		int K = sc.nextInt();
		System.out.println(solve(mat1, mat2, K));

	}

}
content_copyCOPY

https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/pairs-with-given-sum-in-two-sorted-matrices-official/ojquestion