Learn-dsa..in 30 days!



























CC-4 : Find lonely numbers.

Description:

If an integer i exists only once in an array and if i+1 and i-1 do not exist in an array, then i is a lonely integer. Given input array of integers arr, find all lonely integers that exist in it.

Test cases and expected outputs:

Input Parameters Expected outputs
intArray = {8,4,3,2,1,7,10}; Lonely ints: 10
intArray = {3,3,3,4,5}; Lonely ints: none
intArray = {3,3,7,3,2,2,2,9}; Lonely ints: 7,9

Pseudocode:

The java method should accept following input parameters: arr (integer array).
Initialize a variable intFreqMap of type HashMap to hold the characters from arr and their frequencies.
Iterate through arr using a for loop with idx as a loop variable with initial value 0 and increment idx till it reaches arr.length-1:
If intFreqMap does not contain key arr[idx], then put key-value pair arr[idx] and 0 to intFreqMap.
If intFreqMap contains key arr[idx] with value freq, then put key-value pair arr[idx] and freq+1 to intFreqMap.
After completion of above loop, intFreqMap contains keys that are integer from arr and values corresponding to each key is the frequency of that integer in arr.
Initialize a variable lonelyAl of type ArrayList to hold the lonely integers identified in arr.
Iterate through keys of intFreqMap:
Set i to the current integer key of intFreqMap.
If get value of key i in intFreqMap. If the value is equal to 1, it means i then:
 If intFreqMap does not contain i+1 and i-1 as keys, then i is a lonely number. Add i to lonelyAl.
After completion of above loop, lonelyAl contains all the identified lonely integers from arr.
Define integer array lonelyInts with same size as lonelyAl. Iterate through lonelyAl and copy each lonely integer to lonelyInts. Return lonelyInts.

Code:

public int[] hashMapCheckLonely(int[] arr) throws Exception{
	HashMap< Integer,Integer> intFreqMap=new HashMap<Integer, Integer>();
	for (int idx=0; idx < arr.length; idx++) {
		intFreqMap.put(arr[idx], intFreqMap.getOrDefault(arr[idx],0)+1);
	}		
	ArrayList< Integer> lonelyAl=new ArrayList<Integer>();
	Iterator< Integer> itr=intFreqMap.keySet().iterator();
	while (itr.hasNext()) {
		int i=itr.next();
		if (intFreqMap.get(i)==1) {
			if (!((intFreqMap.containsKey(i-1))||(intFreqMap.containsKey(i+1)))){
				lonelyAl.add(i);
			}
		}
	}
	int[] lonelyInts=new int[lonelyAl.size()];
	itr=lonelyAl.iterator(); int idx=0;
	while (itr.hasNext()) {
		int i=itr.next();
		lonelyInts[idx]=i;
		idx++;
	}
	return lonelyInts;	
}

Click here to download and run code and test cases !