sumeet-malik/level2and3

pair with given sum in two sorted matrix (without Hash)

Closed this issue · 0 comments

import java.util.*;

public class Main {

public static int solve(int[][] num1, int[][] num2, int k) {
// write your code here
int size = num1.length * num1[0].length;
int left = 0;
int right = size - 1;
int ans = 0;

while (left < size && right >= 0) {
  int r1 = left / num1.length;
  int c1 = left % num1.length;

  int r2 = right / num2.length;
  int c2 = right % num2.length;

  int sum = num1[r1][c1] + num2[r2][c2];
  if (sum == k) {
    ans++;

    int tempLeft = num1[r1][c1];
    int tempRight = num2[r2][c2];
    
    //we are trying to find the no of element which are equal in their resp matrix
    //and doing leftEqual*rightEqual - 1 (as we already added one to our ans)
    int equalLeft = 1;
    while (left < size - 1) {
      left++;
      r1 = left / num1.length;
      c1 = left % num1.length;
      if (num1[r1][c1] == tempLeft) equalLeft++;
      else {
        left--; //as we reached at next ele but we will still move one step further coz of left++ below, we need to compensate it.
        break;
      }
    }
    int equalRight = 1;
    while (right > 0) {
      right--;;
      r2 = right / num2.length;
      c2 = right % num2.length;
      if (num2[r2][c2] == tempRight) equalRight++;
      else {
        ans+=equalLeft*equalRight-1;
        right++;
        break;
      }
    }
    left++;
    right--;
  } else if (sum > k) right--;

  else left++;
}

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));

}

}