Find the pairs that makes K Complementary in the given array java solution

Find K complementary pairs from the given array

So the problem is, given an array of numbers, you are going to find the pairs whose sum is K.

Say, if you are given 7, 1, 5, 6, 9, 3, 11, -1 and K = 10 then the pairs would be

=> 1 and 9
=> 3 and 7
=> 11 and -1

Here is the O(n) solution for the K complementary problem in java

It turns out, this is not a pure O(n) solution. Can you spot why?


package algorithm;

import java.util.HashMap;
//import java.util.List;
import java.util.Map;

/**
 * Algorithm to find the pairs making the K complementary in O(n) complexity
 * 
 * @author http://gullele.com
 * @see KComplementaryTest.java - a JUnit test for this class
 */
public class KComplementary {
	
	private Map pairs;
	
	public static void main(String[] args) {
		KComplementary kcomp = new KComplementary();
		int[] numbers = new int[]{7, 1, 5, 6, 9, 3, 11, -1};
		Integer[][] pairs = kcomp.getKComplementaryPairs(10, numbers);
		
		for (Integer[] thePairs : pairs) {
			System.out.println(" Pairs are "+thePairs[0] + " and " + thePairs[1]);
		}
	}
	
	public KComplementary() {
		this.pairs = new HashMap();
	}
	
	/**
	 * An algorithm to find the pair from the given array that would sum up the given K
	 * 
	 * @note - the algorithm would be done in o(n). First it will run through the whole 
	 * numbers and creates a temporary list of pairs in HashMap with 
	 * (value, sum-value). 
	 * @param sum
	 * @param listOfIntegers
	 * @return
	 */
	public Integer[][] getKComplementaryPairs(int sum, int[] listOfIntegers) {
		
		/*
		 * I could have used the ArrayList assuming the number of pairs we are getting 
		 * is not known, but giving it a little bit of thought, the number of pairs 
		 * is known in advance, at least the maximum we can get is known.
		 * By not using the Array list, the algorithm would run O(n) rather than
		 * O(n**2) since ArrayList.add would would be O(n) by itself 
		 */
		//List complementaryPairs = new ArrayList();
		Integer[][] complementaryPairs = new Integer[listOfIntegers.length][2];
		//First fill up the pairs with the complementary numbers
		for (int number : listOfIntegers) { //O(n) complexity
			this.pairs.put(number, sum-number);
		}
		
		//then filter out the pairs that don't have corresponding complementary number
		int index = 0;
		for (int number : listOfIntegers) { //O(n) complexity 
			int complementary = sum - number;
			//check if this key exists in the pairs
			if ( this.pairs.containsKey(complementary) ) {
				//Had I used array List this would have been used
				//Integer[] comps = {number, complementary};
				//complementaryPairs.add(comps); //this is O(n)
				complementaryPairs[index][0] = number;
				complementaryPairs[index][1] = complementary;
				index ++;
			}
		}
		//System.out.println(index);
		//Now trim the array since we know the exact record
		Integer[][] trimmed = new Integer[index][2];
		
		index = 0;
		for (Integer[] item : complementaryPairs) { //O(n) complexity
			if (item[0] != null) {
				trimmed[index][0] = item[0];
				trimmed[index][1] = item[1];
			}
			index++;
		}
	
		//Total complexity O(n)+O(n)+O(n) ==> O(n)
		
		//had I used arrayList this would have been used
		//return complementaryPairs.toArray(new Integer[0][0]);
		return trimmed;
	}
}


The above solution runs and would do the job without a problem. But it is not linear solution as it claims to be.

I have got another solution that would explain why and comes up with a solution for it. Check it out here

You can see the jUnit for this class also at here

Using mvn for creating and running a boilerplate minimal java application

It is almost a must to use mvn or any other build tool when dealing with java.

With mvn you can start a minimal simple all included java application and you run that too.. Just follow this. I will assume you are on linux or mac environment for this and also I am assuming you already have maven installed
Create a new folder and say mavenrocks

mkdir mavenrocks

Then add the following

mvn archetype:generate

What it does is, it will use a plugin to create a boilerplate application that holds basic src files along with standard directory structure.
if you do the listing on the created folder you will see:

.
./pom.xml
./src
./src/main
./src/main/java
./src/main/java/com
./src/main/java/com/gullele
./src/main/java/com/gullele/App.java
./src/test
./src/test/java
./src/test/java/com
./src/test/java/com/gullele
./src/test/java/com/gullele/AppTest.java
./target
./target/classes
./target/classes/com
./target/classes/com/gullele
./target/classes/com/gullele/App.class
./target/maven-status
./target/maven-status/maven-compiler-plugin
./target/maven-status/maven-compiler-plugin/compile
./target/maven-status/maven-compiler-plugin/compile/default-compile
./target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst
./target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst

and to run it

mvn execute:java -Dexec.mainClass="com.gullele.App"

Check if there are three numbers a, b, c giving a total T from array A

I got this question while helping a friend on the course work. It is relatively simple question. But the way how it is approached can make a difference on efficiency.

The question is, given an array of numbers, you are to find if there are three numbers that would total the given number T.

If done in a very naive way, it can soar to o(n^3) like having three loops and checking the sum inside the third loop.. well.. this is a no no..

I have approached it in a log n ( for sorting) and n for (searching) approach..


package algorithm;

import java.util.Arrays;

/**
 * Given an array of integers, find if there are three numbers that would sum up to the 
 * number T
 * 
 * @author http://gullele.com
 *
 */
public class ThreeNumbersSummingT {
	public static void main(String[] args) {
		int[] test = new int[]{1,3,4,5,10,12, 18};
		ThreeNumbersSummingT summt = new ThreeNumbersSummingT();
		
		int[] response = summt.findThreeNumbers(test, 29);
		
		if (response.length > 1) {
			for(int num : response) {
				System.out.println(num);
			}
		} else {
			System.out.println(":( Couldn't find those three gems");
		}
				
	}
	
	public int[] findThreeNumbers(int[] nums, int t) {
		
		int[] indexes = new int[1];
		if (nums.length == 0 || nums.length <= 2) {
			return indexes;
		}
		
		//for primitive this would be quick sort so we have nlogn
		Arrays.sort(nums);
		
		int minIndex =0;
		int maxIndex = nums.length-1;
		int current = 1;
		while (minIndex != maxIndex) {
			if (nums[minIndex] + nums[maxIndex] + nums[current] == t) {
				int[] summingNumbers = new int[3];
				summingNumbers[0] = nums[minIndex];
				summingNumbers[1] = nums[current];
				summingNumbers[2] = nums[maxIndex];
				return summingNumbers;
			}
			
			int lookingFor = t-(nums[minIndex] + nums[maxIndex]);
			//if the number being sought is beyond the max, then jack up the min index
			if (lookingFor >= nums[maxIndex]) {
				minIndex++;
				current = minIndex + 1;
			} else if (nums[minIndex] + nums[maxIndex] + nums[current] < t) {
				current++;
			} else {
				maxIndex--;
				current = minIndex + 1;
			}
			
		}
		
		return indexes;
	}
}


asadmin-command-unknown-in-glassfish-ee-application

am a great user of tomcat when it comes to Java web application. I had fun with it. Being fast and allowing a bunch of things to be done by myself.. that being said, I am a regular user of glassfish as well. Specially the later version 3 looks awesome in a lot of ways..

I will try to use this blog to amend any hiccups whenever they appear and a bit of more tutorials as well.

The first one is the command line friend asadmin.

On the new version it will be found on

/glassfish-main-directory/glassfish3/glassfish/bin

Being on this directory if you issie

./asadmin

You will get the command line for it.
To add it to your path so that you can use it from any where in your terminal, just add it to your path

open your ~/.bash_profile or .bash_rc [create it if it doesnt exist and add the above directory at the end of it separated by appropriate directory separator.

That is it..

re-structre

Change default source directory src/java in eclipse for java project

Prepare directory structure for maven by changing the default src

Probably you are using maven and wanted to change the directory structure.

Since maven recommends the standard src/main/java src/main/resource you might want to change it that way

Here is how to do it in eclipse.

First create the folder structure on the project in which ever way you would want to do it. I would use simple command like mkdir folderName to create it.

1. right click on the project, and hit refresh, make sure the folders you created are listed there.

2. Right click on the project, select properties and select java build path

3. Go to source tab

4. select and remove the current source folder, by default it would be src folder

5. Hit the Add newthen select your folder structure there.

maven directory structure

maven directory structure

This would change the original structure of the your java project from src to the one maven compatible.

See how to use maven to create starter boilerplate application
Get started with step by step j2ee and maven tutorial using eclipse

Can you solve these cool algorithm problems? See their solution as well

How do you find the maximum consecutive sum from the given array

You are given billion numbers and to look for a couple of missing numbers

From list of numbers in array, find those that are complementary to the given number

test

Wanted but not invoked: However, there were other interactions with this mock: ->

Wanted but not Invoked Error in mockito and its solution

This happens with mockito when trying to verify the invocation on an object with specific method.

But what happens is you have interacted with other method of that object but not the one mentioned.

If you have an object named CustomerService and say it has two methods named saveCustomer() and verifyExistingCustomer()

And mockito looks something like

verify(customerService, atleast(1)).verifyExistingCustomer(customer), 

But in your actual service you called the saveCustomer() at least once.. BINGO you would get that error.

Also Recommended for you

See how you can get started with mockito with simple example

Do you like Algorithms?

Find K complementary numbers from given array

Can you form the longest palindrome from the given random characters?