Friday, 1 May 2020

longest common prefix (leetcode) java implementation

Hi Lets solve the Leet code problem "Longest Common Prefix"

Problem :

        we were given an array of string  we should return the Longest common prefix

 Input: ["flower","flow","flight"]
Output: "fl
here the largest matching prefix is fl
Code:
Test Cases:

if you have any query or suggestion please feel free to post a comment

Thursday, 30 April 2020

palindrome Number (leet code) implementation in java

Hi  in this blog post we are going to implement the leet code problem palindrome Number 

Problem Statement :

       given a number we have to determine weather it is palindrome or not  , (i.e) it reads the same if reads backwards as well as forwards 

for eg 121 is palindrome 


how do we solve the problem , there are lot of ways to solve the problem the approach i used was Two pointer approach , using two pointer one at the beginning and another at the end if they didn't match then it is not a palindrome if it matches then we increment the starting pointer and  decrement the endpointer until both pointers meet 

Lets visually see it 





this is how the number looks like  now we add two pointers one at the beginning of the array and another  at the end of the array 



so we are comparing both their values  if they are same then  we increment the start pointer and decrement the endpointer   since both pointers meet we exit the loop and returns true that the given number is a palindrome


Time Complexity:

             the time complexity is o(n)  since we are comparing it in one go 

             space complexity is o(n) since we use a character array to store number 



Code





TestCases:


in the above  we can see the test cases with coverage , if you have any doubts or opinions please comment 

Thursday, 9 April 2020

GCP SQL (Postgres) integration with spring boot

here we will see how to connect to a  postgres instance in GCP , using spring boot

add these dependencies in the pom.xml










and add the following properties in application.properties file





and one more thing we have to install SDK and authenticate your account

https://cloud.google.com/sdk/gcloud/reference/auth/login. ,  follow this link to authenticate. now we are connected to GCP    





Sunday, 8 July 2018

Deep cloning using copy constructor in java

previous i have shown how to do a shallow and deep cloning ion java , Though i uses Deep cloning in my project . Deep cloning has lot of drawbacks and i hate the casting ,and exception handling in cloning
Let's see with an example


There are two classed in this Example , Person.java and Adress.java  Person.java has an Adress
package sample;
import  com.solo.Adress;public class Person {

    private String name;    private String age;    private Adress adress;
    public String getName() {
        return name;    }

    public void setName(String name) {
        this.name = name;    }


    public String getAge() {
        return age;    }

    public Adress getAdress() {
        return adress;    }

    public void setAdress(Adress adress) {
        this.adress = adress;    }

    public void setAge(String age) {
        this.age = age;    }

    @Override    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                  "adress=" + adress+ '\'' +
                '}';    }

    public Person(String name, String age, Adress adress) {
        this.name = name;        this.age = age;        this.adress = adress;    }

    public  Person(Person thatperson) {
        this.name = thatperson.getName();        this.age = thatperson.age;        this.adress = new Adress(thatperson.getAdress());    }


}


package com.solo;
public class Adress {
    private String streeetname;    private  String doornumber;    private  String pincode;
    public String getStreeetname() {
        return streeetname;    }

    public void setStreeetname(String streeetname) {
        this.streeetname = streeetname;    }

    public String getDoornumber() {
        return doornumber;    }

    public void setDoornumber(String doornumber) {
        this.doornumber = doornumber;    }

    public String getPincode() {
        return pincode;    }

    @Override    public String toString() {
        return "Adress{" +
                "streeetname='" + streeetname + '\'' +
                ", doornumber='" + doornumber + '\'' +
                ", pincode='" + pincode + '\'' +
                '}';    }

    public void setPincode(String pincode) {
        this.pincode = pincode;    }

    public  Adress(String streeetname, String doornumber, String pincode) {
        this.streeetname = streeetname;        this.doornumber  = doornumber;        this.pincode = pincode;    }

    public  Adress(Adress that) {
        this.pincode = that.pincode;        this.doornumber = that.doornumber;        this.streeetname = that.streeetname;    }


}





Lets check if it is really working


package sample;

import com.solo.Adress;

public class Main {


    public static void main(String[] args) {
        Adress adress = new Adress("dandesshwaram","10","629003");      Person p1 = new Person("solomon","31",adress);      System.out.println(p1);      System.out.println("-------------------- After changing the Adress---------------");      System.out.println("taking copy constructor");      Person p2 = new Person(p1);
      System.out.println("changing persons 1 adress");      p1.getAdress().setDoornumber("5");      p1.getAdress().setPincode("600032");
      System.out.println("checking if the changes has affected the second reference");
      System.out.println(p1);      System.out.println(p2);    }
}





Lets run and see if is working


Person{name='solomon', age='31'adress=Adress{streeetname='dandesshwaram', doornumber='10', pincode='629003'}'}
-------------------- After changing the Adress---------------
taking copy constructor
changing persons 1 adress
checking if the changes has affected the second reference
Person{name='solomon', age='31'adress=Adress{streeetname='dandesshwaram', doornumber='5', pincode='600032'}'}
Person{name='solomon', age='31'adress=Adress{streeetname='dandesshwaram', doornumber='10', pincode='629003'}'}



oops it is working easy as a PIE



Saturday, 4 June 2016

insertion sort implementation in java

in this  blogpost we will see what is insertion sort how it  can be implemented in java





what we have is an unsorted array , first we have to split the array in to two indices from 0 -> sorted array and from 0+1 -> length of the array an unsorted array  , so in the above array 4 is sorted and the rest of the array is unsorted so we are increasing the sorting array in the next iteration we are increasing the index to 1 , and then from end of the sorting array to the beginning of the sorted array we are comparing each elements we are comparing each elements if they are not sorted then we swap their positions , here the sorted array is from 0-1 and the elements are 4, 3 since it is not sorted we are swapping the two elements after swapping 


now 0-1 is sorted and we move the sorted index to 2 , and there are three elements then from index 2 to 0 we comparing if all the elements are sorted , first we compare the index 2 with 1 since it is  not sorted we swap the elements and move the cursor to one then we compare  index 1 with 0 since those elements were not sorted we swap them  after that the array will look like this 




then we increase the sorted index and repeat the process 


lets see how the code looks Like 





and it was run successfully against these following Test cases 











Sunday, 17 April 2016

Doubly Linked List implementation in Java

In this blog post we will see  how to implement LinkedList in java,  first we have to understand how Linked List differs from ArrayList  , This is how Array List is stored in memory




but Link List just has a reference to the next node ,  in the case of doubly Linked a Node has pointer to both previous element and the next element , if the node previous Node is null then it is the head node , if its next node is null then it is the tail or Last element 



Lets see the implementation and  the Test cases 



















as you can see the implementation is straight forward , nothing complex the entire code and Test cases can be found in the following repo





Saturday, 12 March 2016

CREATING A ZIP file in JAVA

package zip;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CreatingZip {
    public static void main(String[] args) {
FileOutputStream fos;
try {
    fos= new FileOutputStream("/home/myname/kkk.zip");
    ZipOutputStream zis = new ZipOutputStream(fos);
    File file = new File("/home/myname/solo.txt");
    File file2 = new File("/home/myname/innerfolder/innerfile.txt");
    List<File> filelist= new ArrayList<File>(); 
    filelist.add(file2);
    filelist.add(file);

    for(File filename:filelist){
    FileInputStream FS = new FileInputStream(filename);
     System.out.println(filename.getAbsolutePath());
     System.out.println(filename.getPath());
     System.out.println(filename.getName());
    ZipEntry zipentry = new ZipEntry(filename.getPath());
    zis.putNextEntry(zipentry);
    int i;
    while((i=FS.read())>-1){
        zis.write(i);
    }
   

    }
   

    zis.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}       
     
       

}}

Tuesday, 8 March 2016

EXTRACTING A ZIP FILE IN JAVA

in this tutorial we are going to see how to extract a zip file using java. there are two ways to extract zip files

1)zipinputstream
2)zipfile

here we use the zip file

package zip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Multizipcreation {

    public static void main(String[] args) {
        File file = new File("/home/solomon/pdf.zip");
        try {
            byte[] buffer = new byte[1024];
            ZipFile zipFile = new ZipFile(file);
            File outputfolder = new File(file.getParent()+File.separator+"op");
            if(!outputfolder.exists()){
                outputfolder.mkdirs();
            }
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while(entries.hasMoreElements()){
             ZipEntry entry = entries.nextElement();
             InputStream is = zipFile.getInputStream(entry);
             extract(is,entry,outputfolder);
           
            }
           
            zipFile.close();
       
           
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
               

    }

    private static void extract(InputStream is, ZipEntry entry,File op) {
     try {
       
        FileOutputStream fos = new FileOutputStream(op+File.separator+entry.getName());

       
        int i;
        while((i=is.read())>-1){
        fos.write(i);
        }
        fos.close();
       
       
    } catch ( IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       
    }

}

Sunday, 11 October 2015

XML PARSING IN PYTHON USING MINIDOM

parsing an xml in python using minidom

xml file to be parsed

<?xml version="1.0"?>
<company>
    <employee id="1001">
        <firstname>yong</firstname>
        <lastname>mna</lastname>
        <nickname>mrreferenc</nickname>
        <salary>100000</salary>
    </employee>
    <employee id="2001">
        <firstname>dev</firstname>
        <lastname>journal</lastname>
        <nickname>general</nickname>
        <salary>200000</salary>
    </employee>
       <employee id="2002">
        <firstname>darth</firstname>
        <lastname>vader</lastname>
        <nickname>anakan</nickname>
        <salary>2000</salary>
    </employee>
<employee id="2003">
        <firstname>obi</firstname>
        <lastname>van kanobi</lastname>
        <nickname>ben kanobi</nickname>
        <salary>1500</salary>
    </employee>
<employee id="2009">
        <firstname>hello</firstname>
        <lastname>world</lastname>
        <nickname>wasteland</nickname>
        <salary>20</salary>
    </employee>
</company>

CODE:
   
__author__ = 'solomon'
from xml.dom import minidom

xmlfile= minidom.parse('/home/solomon/solo.xml')
employee = xmlfile.getElementsByTagName("employee")
for emp in employee:
    if(emp.hasAttribute('id')):
        print emp.getAttribute('id')
    firstname= emp.getElementsByTagName('firstname')[0]
    print "firtname" + firstname.childNodes[0].data
    lastname=emp.getElementsByTagName('lastname')[0]
    print 'lastname'+lastname.childNodes[0].data
    salry=emp.getElementsByTagName('salary')[0]
    print "salary"+salry.childNodes[0].data
 
 
OUTPUT:
 
/usr/bin/python2.7 /home/solomon/PycharmProjects/untitled/domparsing.py
1001
firtnameyong
lastnamemna
salary100000
2001
firtnamedev
lastnamejournal
salary200000
2002
firtnamedarth
lastnamevader
salary2000
2003
firtnameobi
lastnamevan kanobi
salary1500
2009
firtnamehello
lastnameworld
salary20

Process finished with exit code 0
 

Sunday, 4 October 2015

OBJECT SORTING IN JAVA COMPARATOR VS COMPARABLE

comparable and comparators are two interfaces provided by java to Sort custom Objects . Here i'm going to explain to you how to sort a person class using java


package sample;
import  com.solo.Adress;public class Person implements Comparable<Person> {

    private String name;    private String age;    private Adress adress;
    public String getName() {
        return name;    }

    public void setName(String name) {
        this.name = name;    }


    public String getAge() {
        return age;    }

    public Adress getAdress() {
        return adress;    }

    public void setAdress(Adress adress) {
        this.adress = adress;    }

    public void setAge(String age) {
        this.age = age;    }


    public Person(String name, String age, Adress adress) {
        this.name = name;        this.age = age;        this.adress = adress;    }


    @Override

    public int compareTo(Person person) {
        return this.name.compareTo(person.getName());    }
}

THis is a simple example for comparable interface it is self explanatory .it has one method

very simple and used for normal sorting operations 


what if you want more than two sorting techniques i.e you want to sort by both age and salry 

that's where comparator kicks in
 
package sample;
import java.util.Comparator;
public class Agecomparator implements Comparator<Person> {
    @Override    public int compare(Person person, Person t1) {
        return person.getAge().compareTo(t1.getAge());    }
}

System.out.println("before Sorting");printperson(personList);
System.out.println("....................sorting........................");
Collections.sort(personList,new  Agecomparator());
System.out.println("....................... After sorting --------------------------");
printperson(personList);


before Sorting
solomon
anish
bob
zolton
farage
hercules
....................sorting........................
....................... After sorting --------------------------
farage
hercules
zolton
anish
solomon
bob