Thursday, 14 June 2018

O(n^2) vs O(n) techniques for finding the max count of a digit in the given numerical String.


Hello Buddies

Came across this question related Java String handling, so thought of sharing.

Question:
Given a string made up of n number of digits, find the digit having the maximum number of occurrence.
Eg. "12333123654"
Here, 3 is the digit being repeated for the maximum number of times.

Answer:
First approach can be to scan the string as a character array, maintain a map that can update the occurrence count. In the end find the max value and then the corresponding key.


Question:
What is the complexity of this solution?

Answer:
O(n^2) since we are iterating and using contains check.


Question:
Any better approach?

Answer:
Solution with O(n) complexity, i.e. having a lookup array.
We have digits 0 to 9, which can be related to each index of an array. For the values, update the occurrence count in the values.

For complete solution, refer to this link.

Happy Coding!!


Friday, 8 June 2018

Cloning in java - An interviewer's perspective






Wassup Buddies!



'Cloning' is the topic we will be cloning down for this blogpost.


To save time and memory, coders often prefer to re-use already existing objects. Commonly, a new reference pointing to an existing object, or talking about veterans of Java, techniques like cloning are used.


Digging deeper in this context, we will understand what are the repercussions and whats are the various ways of cloning. Core java interviewers find it an interesting topic to engulf the candidates by asking various pros and cons.



I have placed the sample Java class that I created for my understanding and the differentiation of types, here



Please feel free to get your hands dirty. Many of our readers might find the topic repetitive, but I hope they will find a new perspective of seeing or explaining the concepts or would love to share their thoughts and suggestions for improving the knowledge of others.




A brief primer for better understanding of the code is as follows:



Scenario 1: Assigning the reference.


Test ob1 = new Test();


Where Test.java is -


class Test {
int var1, var2;
Dummy dummy = new Dummy();
Test() {
var1 = 10;
var2 = 20;
dummy.aVar = 30;
dummy.bVar = 40;
}
}


Simply straight forward, an object is having its reference.

ob1 original -- 10 20 30 40



Scenario 2: Creating a new reference for the same object, using the earlier created reference.


Test ob2 = ob1;


Now make some changes using the second reference to see the impact on the object created.


ob2.var1 = 100;
ob2.dummy.aVar = 1000;


What do we get?

ob1 original -- 10 20 30 40
ob1 changed -- 100 20 1000 40
ob2 original -- 100 20 1000 40


So clearly, as expected, reference will impact the original object.




Scenario 3: Shallow Cloning


CloneableTest cloneableTest = new CloneableTest();


Where CloneableTest.java is -


class CloneableTest implements Cloneable {
int var1, var2;
Dummy dummy = new Dummy();
CloneableTest() {
var1 = 10;
var2 = 20;
dummy.aVar = 30;
dummy.bVar = 40;
}
public Object clone()
throws CloneNotSupportedException {
return super.clone();
}
}


Note: For using cloneableTest.clone(), we need to have the class implementing Cloneable interface, else we will get ''CloneNotSupportedException".



Bringing in a new reference for testing -


CloneableTest newCloneable = null;
try {
newCloneable = (CloneableTest) cloneableTest.clone();
newCloneable.var1 = 99;
newCloneable.var2 = 99;
newCloneable.dummy.aVar = 99;
newCloneable.dummy.bVar = 99;
} catch (CloneNotSupportedException e) {
// e.printStackTrace();
System.err.println
("Exception since Cloneable interface is not implemented!!");
}


Changes have been made, but what about the original object? Let's check!



Original Before : 10 & 20 & 30 & 40

Cloned   : 99 & 99 & 99 & 99
Original After : 10 & 20 & 99 & 99


Hence take away from this example - original primitive attributes won't change, but non primitives will change. 

Still the cloned object is not yet completely change proof.



Scenario 4: Deep Cloning



CloneableDeepTest cloneableDeepTest = new CloneableDeepTest();

Where CloneableDeepTest.java is -

class CloneableDeepTest implements Cloneable {
int var1, var2;
Dummy dummy = new Dummy();
CloneableDeepTest() {
var1 = 10;
var2 = 20;
dummy.aVar = 30;
dummy.bVar = 40;
}
public Object clone()
throws CloneNotSupportedException {
CloneableDeepTest cloneableDeepTest
= (CloneableDeepTest) super.clone();
cloneableDeepTest.dummy = new Dummy();
return cloneableDeepTest;
}
}


Bringing in new reference again -



CloneableDeepTest cloneableDeepTest2 = null;
try {
cloneableDeepTest2 =
(CloneableDeepTest) cloneableDeepTest.clone();
cloneableDeepTest2.var1 = 55;
cloneableDeepTest2.var2 = 66;
cloneableDeepTest2.dummy.aVar = 77;
cloneableDeepTest2.dummy.bVar = 88;
} catch (CloneNotSupportedException e) {
// e.printStackTrace();
System.err.println
("Exception since Cloneable interface is not implemented!!");
}

What should be the impact on the original object now? Let's check!


Original Before : 10 & 20 & 30 & 40

Cloned   : 55 & 66 & 77 & 88
Original After : 10 & 20 & 30 & 40


Sigh! The cloned object still retains the expected original values for both primitive and non primitive attributes.


Major difference between the implementation of shallow and deep clonings can be seen in the overridden clone() methods -

For shallow we simply call super.clone() as follows -

public Object clone()
throws CloneNotSupportedException {
return super.clone();
}


While for deep cloning, we need to go a bit further and control the way how inner objects are being generated as follows -

public Object clone()
throws CloneNotSupportedException {
CloneableDeepTest cloneableDeepTest =
(CloneableDeepTest) super.clone();
cloneableDeepTest.dummy = new Dummy();
return cloneableDeepTest;
}

That's all I have for now.

Happy Coding!!

Sunday, 15 April 2018

How to read and write a CSV file using core java?


Hello Buddies.

CSV: CSV is a comma separated values file which allows data to be saved in a table structured format


Let's try to read a CSV file using java, filter out the required rows and create a new CSV per our own requirements.


Input - Provided as a path for the file having below details -


ID NAME AGE GENDER OCCUPATION ADDRESS
1 ABC 22 M SE IN
2 DEF 32 F SE US
3 ABC 12 M SE UK
4 DEF 42 F SE IN
5 ABC 52 M SE US
6 DEF 53 F SE UK
7 ABC 60 M SE IN
8 DEF 67 F SE US
9 ABC 74 M SE UK
10 DEF 81 F SE IN
11 ABC 88 M SE US








We will filter out the people living in India and will have a new CSV only for those people.

Here's a code snippet -

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CSVReader {

 private static String mainPath = "C:\\\\Users\\\\namit.sharma\\\\Downloads\\\\";

 public static void main(String[] args) throws IOException {

  FileReader fileReader = new FileReader(new File(mainPath + "sampleExcel1.csv"));

  BufferedReader bufferedReader = new BufferedReader(fileReader);

  String string;
  do {
   string = bufferedReader.readLine();
   if (null != string) {
    System.out.println(string);
    filterForIndians(string);
   }
  } while (null != string);

  bufferedReader.close();

 }

 private static void filterForIndians(String string) throws IOException {
  File file = new File(mainPath + "fileredCsv.csv");
  if (file.exists()) {
   file.delete();
  }
  FileWriter fileWriter = new FileWriter(new File(mainPath + "fileredCsv.csv"),true);
  if ("IN".equals(string.split(",")[5])) {
   BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
   bufferedWriter.write(string+"\n");
   bufferedWriter.close();
  }
 }

}


Now we can check the generated csv. It will have the desired rows -

1 ABC 22 M SE IN
4 DEF 42 F SE IN
7 ABC 60 M SE IN
10 DEF 81 F SE IN

How to count the number of leaves in a binary tree?


Hello Buddies.


Here's a quick code snippet for finding the number of leaves in a 'Binary Tree', after a node gets deleted!





Have a look-

Input -

5
-1 0 0 1 1
1


Input description -

Line 1: No. of nodes in Binary Tree
Line 2: All the nodes' parents, where -1 means no parent - root, 0 means root as parent.
Line 3: Node at which this value exists, remove it.


Node to remove -



public class TreeProblem {
 private static int count = 0;

 public static void main(String args[]) throws Exception {

  Scanner scanner = new Scanner(System.in);
  int numOfNodes = scanner.nextInt();
  scanner.nextLine();
  String intStr = scanner.nextLine();
  String[] array = intStr.split(" ");
  int[] arr = new int[array.length];
  for (int i = 0; i < numOfNodes; i++) {
   arr[i] = Integer.valueOf(array[i]);
  }
  int nodeToDelete = scanner.nextInt();

  // create a tree
  Node root = null;
  int valueIndex = 0;
  Node current = null;
  for (int i = 0; i < numOfNodes; i++) {
   if (arr[i] == -1) {
    root = new Node(valueIndex++);
    current = root;
   } else {
    if (arr[i] == current.value) {
     if (null == current.left) {
      current.left = new Node(valueIndex++);
     } else if (null == current.right) {
      current.right = new Node(valueIndex++);
      current = current.left;
     }
    }
   }
  }

  // scan the tree for deleting the node
  // it clearly means we have to ignore the leaves at that node, for the remaining
  // keep the count going

  treetraversal(root, nodeToDelete);

  System.out.println("Remaining leaves = " + count);
  scanner.close();
 }

 private static void treetraversal(Node root, int nodeToDelete) {
  if (null == root) {
   return;
  }
  System.out.println("-- " + root.value);
  if (root.value == nodeToDelete) {
   return;
  }
  if (null != root.left) {
   treetraversal(root.left, nodeToDelete);
  }
  if (null != root.right) {
   treetraversal(root.right, nodeToDelete);
  }
  if (null == root.left && null == root.right) {
   count++;
  }
 }

}

class Node {

 int value;
 Node parent, left, right;

 Node(int value) {
  this.value = value;
 }
}

Friday, 30 March 2018

SSH Tutorial - How to access UNIX server from WINDOWS client

Hello Buddies.

Here is a quick tutorial to get hands-on experience in accessing a remote machine.
It can either be a case of a remote machine being used as a server or as a storage location.

In case your remote machine is having Windows platform, things become really straightforward. Just need to use MSTSC – Remote login through your windows machine, enter the credentials, and boom, you are already on the remote machine!

Complications occur when the remote machine is UNIX based.

For the same, this tutorial will be based on the below scenarios –

  • Remote machine: UNIX based – here it’s Fedora
    • Remote machine will be hosting a simple HTML page
    • It will be using Apache HTTPD as the server
    • To enable access, it will use SSH
  • Client machine: Windows-based
    • It will use putty for SSH access
    • It will also update the HTML content of the remote server


Sounds interesting?
 Cool! Let’s begin the discussion.


All About Remote

Using Apache HTTP Server project here.

Install:         sudo dnf install httpd
Start:           sudo systemctl start httpd.service
Check:        using http://localhost.

The root directory of your web server is now situated at /var/www/html/ with root as the owner.

Comment out all the lines in /etc/httpd/conf.d/welcome.conf default page landing. 

Create an index.html file with your content in the /var/www/html/ directory:

<html>
    <head>
        <title>Hello world</title>
    </head>
    <body>
        Hello world!
    </body>
</html>

Now, when you visit http://localhost, you will see your new index page.

Yeah! It looks cool! Changes are picked up nicely and easily!


Can I access this web page from any other machine?


Here comes a tricky part. By default, each OS has restrictions over ports, and firewalls as well.
So, you need to, first of all, find the public IP of your system and allow access to a port that would be exposed.









In a UNIX machine, you can check the iptables, for the status of the ports.

  iptables -L

Also open the port 80, for the apache server.

  iptables -I INPUT -p tcp --dport 80 -j ACCEPT

For the IP address of the machine, use ifconfig.

Boom!

Hit the URL from any machine now – http://192.168.xx.xx:80

And you will see the content !!!





 







What if I want to change the content from my client machine?


Here comes another tricky part, that surely demands at least one hands-on experience.

  • Get openssh-server on your server machine 
    •  sudo dnf install openssh-server






  • Start the ssh service
    • sudo systemctl start sshd.service
  • By default, it will use port 22. Remember this!
  • Also, doing some authentication stuff here.
    • Use keygen command to generate an RSA private key at the server side.
    •  # ssh-keygen -t dsa
  • Save the key, for now, bypass the passphrase as empty.


Use the saved private key in your windows client now. How? 
Check this below!

  • Install putty in your windows client.
  • Open puttyGen.
  • Load the imported private key.
  • Open putty, enter the IP address of the server machine.
  • Remember the default port number? Yes, correct. It should be 22.


Hit it. Boom! You are in the server machine now.

Remember where your HTML content was being picked up from?
Yup, correct!

Update the content at /var/www/html/ 


















Refresh the web pages, and you will have new content with you.




















So, this was a quick one! Keep exploring.

And Happy coding!










Featured post

JAVA based project, that can be used to hit DB using JDBC, from WSO2 ESB

Hi Buddies, Here is a small project that will enable you to hit MySQL DB using WSO2 ESB - https://github.com/namitsharma99/customM...

Popular Posts