Skip to main content

Find the number of negative integers from row wise or column wise from a sorted matrix

Find the number of negative integers from row wise or column wise from a sorted matrix
This is a frequently asked question for a experienced interview.
Here i am trying to solve this in two different ways, normal way and an optimised method.

Main Class

/**
 * 
 */
package com.rakesh.matrix.bo;

/**
 * @author Rakesh KR
 * @since  August 19th 13:15 2k17
 */
public class RunMatrix {

 public static void main(String[] args) {
  
  MatrixUtils matrixUtils = new MatrixUtils();
  
  try{
   
   System.out.println("------ Matrix ------");
   
   matrixUtils.makeMartix();
  // matrixUtils.printMatrix();
   
   matrixUtils.sortRowMatrix();
   matrixUtils.transpose();
   matrixUtils.sortRowMatrix();
   matrixUtils.transpose(); 
  // matrixUtils.printMatrix();
   
   long t1 = System.currentTimeMillis();
   System.out.println("NegativeNumbers Count Normal    Way : "+matrixUtils.countNegativeNumbersNormal());
   long t2 = System.currentTimeMillis();
   System.out.println("Time for Normal Way :"+(t2-t1)+" ms");
   t1 = System.currentTimeMillis();
   System.out.println("NegativeNumbers Count Optimized Way : "+matrixUtils.countNegativeNumbersOptimized());
   t2 = System.currentTimeMillis();
   System.out.println("Time for Optimized Way :"+(t2-t1)+" ms");
   
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   matrixUtils = null;
  }

 }

}


Sub Class

/**
 * 
 */
package com.rakesh.matrix.bo;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

/**
 * @author Rakesh KR
 * @since  August 19th 13:17 2k17
 */
public class MatrixUtils {
 
 public int m;
 public int n;
 public int[][] matrix;
 
 public void makeMartix(){
  
  Scanner sc = new Scanner(System.in);
  
  try{
   System.out.println("Size Of Matrix (mxn) : ");
   n = sc.nextInt();
   m = sc.nextInt();
   matrix = new int[n][m];
  // System.out.println("Enter the details to matrix : ");
   int    max    = 99;
   int    min    = -99;
   Random random = new Random();
   for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
  //   matrix[i][j] = sc.nextInt();
     matrix[i][j] = random.nextInt(max + 1 -min) + min; 
    }
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   sc.close();
  }
  
 }
 
 public void printMatrix(){
  
  try{
   System.out.print("The matrix is : \n");
   for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
     System.out.print(" "+matrix[i][j]+" ");
    }
    System.out.print("\n");
   }
   System.out.print("\n");
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   
  }
  
 }
 
 public void sortRowMatrix(){
  
  try{
   for(int i=0; i<matrix.length; i++){
    Arrays.sort(matrix[i]);
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   
  }
  
 }
 
 public void transpose(){
     for (int i = 0; i < matrix.length; i++) {
         for (int j = i; j < matrix[0].length; j++) {
             int tmp1 = matrix[i][j];
             int tmp2 = matrix[j][i];
             matrix[j][i] = tmp1;
             matrix[i][j] = tmp2;
         }
     }
 }
 
 public int countNegativeNumbersNormal(){
  
  int count = 0;
  
  try{
   for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
     if(matrix[i][j]<0){
      count ++;
     }
    }
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   
  }
  
  return count;
 }
 
 public int countNegativeNumbersOptimized(){
  
  int count = 0;
  
  try{
   int i = 0;
   int j = m-1;
   while(j>=0 && i<n){
    if(matrix[i][j]<0){
     count+=(j+1);
     i+=1;
    } else{
     j-=1;
    }
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   
  }
  
  return count;
 }
 
}

Methods:

makeMartix()
This method is used to make a random matrix which consists of positive and negative vales. 
Having min value as -99 and max value as 99.
printMatrix()
This method is used to print an mxn matrix in a user readable manner.
sortRowMatrix()
This method is used to sort an mxn matrix.
transpose()
This method is used to find the transpose of an mxn matrix.
countNegativeNumbersNormal()
An normal way to count the negative numbers from an mxn matrix. 
Its having an 0(n^2) complexity. 
countNegativeNumbersOptimized()
An optimized way to count the negative numbers from an mxn sorted matrix. 

Some tested Results : 
With an 2x2 matrix  :-
------ Matrix ------
Size Of Matrix (mxn) : 
2 2
The matrix is : 
 -53  40 
 -57  10 

The matrix is : 
 -57  10 
 -53  40 

NegativeNumbers Count Normal    Way : 2
Time for Normal Way :0 ms
NegativeNumbers Count Optimized Way : 2
Time for Optimized Way :0 ms

With an 100x100 matrix  :-

------ Matrix ------
Size Of Matrix (mxn) : 
100 100
NegativeNumbers Count Normal    Way : 4906
Time for Normal Way :1 ms
NegativeNumbers Count Optimized Way : 4906
Time for Optimized Way :0 ms

With an 5000x5000 matrix  :-

------ Matrix ------
Size Of Matrix (mxn) : 
5000 5000
NegativeNumbers Count Normal    Way : 12438372
Time for Normal Way :27 ms
NegativeNumbers Count Optimized Way : 12438372
Time for Optimized Way :1 ms

With an 10000x10000 matrix  :-

------ Matrix ------
Size Of Matrix (mxn) : 
10000 10000
NegativeNumbers Count Normal    Way : 49745496
Time for Normal Way :88 ms
NegativeNumbers Count Optimized Way : 49745496
Time for Optimized Way :2 ms

Comments

  1. Advertise what you do with a Home service websites templates from TemplateMonster. Easily customize using our drag-and-drop feature.

    ReplyDelete

Post a Comment

Popular posts from this blog

JSON (JavaScript Object Notation)

JSON (JavaScript Object Notation) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values). It is a common data format with diverse uses in electronic data interchange, including that of web applications with servers. JSON is a language-independent data format. It was derived from JavaScript, but many modern programming languages include code to generate and parse JSON-format data. JSON filenames use the extension .json. Any valid JSON file is a valid JavaScript (.js) file, even though it makes no changes to a web page on its own. Douglas Crockford originally specified the JSON format in the early 2000s. He and Chip Morningstar sent the first JSON message in April 2001. Official website :- https://json.org/

Object serialization in java

Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object. When you want to serialize an object, that respective class should implement the marker interface serializable. It just informs the compiler that this java class can be serialized. You can tag properties that should not be serialized as transient. You open a stream and write the object into it. Code for serialization of a java class : Data.java package com . codetalk . serialization ; import java.io.Serializable ; public class Data implements Serializable { private static final long serialVersionUID = 1L; private String firstName ; private String lastName ; /** * @return the firstName */ public String getFirstName () { return firstName ; } /** * @param firstNam

Amazon Lambda (AWS Lambda)

 AWS Lambda is an event-driven, serverless computing platform provided by Amazon as a part of Amazon Web Services. It is a computing service that runs code in response to events and automatically manages the computing resources required by that code. It was introduced on November 13, 2014. AWS Lambda was designed for use cases such as image or object uploads to Amazon S3, updates to DynamoDB tables, responding to website clicks, or reacting to sensor readings from an IoT connected device.  Unlike Amazon EC2, which is priced by the hour but metered by the second, AWS Lambda is metered by rounding up to the nearest millisecond with no minimum execution time. AWS Lambda can also be used to automatically provision back-end services triggered by custom HTTP requests, and "spin down" such services when not in use, to save resources. Since December 2020 Lambda supports Docker containers through ECR up to 10 GB in size. Official website :- https://aws.amazon.com/lambda