Bank of America Interview Question
Software EngineersCountry: United States
use hashtable to count occurences.
Then scan the hashtable and maintain two variables: "min" and "secondMin".
Return "secondMin" in the end.
you are suggesting if i have to find 10000000th smallest element i have to maintain 10000000 variables and return 10000000th min variable in the end.
quite reasonable observation.
really, in simple case (as in the task), we can maintain two variables, and that will be enough.
In general case ("get nth least common element from array"), of course it is necessary to change the solution as follows:
introduce an extra data structure, e.g. priority queue (min heap), put all the values from hashtable into priority queue, and then call delete-min n times.
no !!! to find the k-th smallest item you use the selection algorithm (i.e. quick-select) which is O(n). hahaha
!) Hashing
2) If the elements in the array are of fixed range, then do counting sort
3 Binary search tree.+ inorder -> O(nlogn)
4) BST + Heap -> O(nlogn)
public class SecondLeastCommonElement
{
public static void main( String[] args )
{
int[] array = { 5, 5, 4, 5, 4, 6, 6, 6, 1, 3, 3, 4, 4, 5, 4,3,3 };
for( int i = 0; i < array.length - 1; i++ )
{
for( int j = i + 1; j < array.length; j++ )
{
if( array[i] > array[j] )
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
int firstLeast = array[0], secondLeast = array[0];
int firstLeastCount = Integer.MAX_VALUE, secondLeastCount = Integer.MAX_VALUE, count = 1;
for( int i = 1; i < array.length; i++ )
{
if( array[i - 1] != array[i] )
{
System.out.println( array[i - 1] + "=" + count );
if( firstLeastCount > count )
{
firstLeastCount = count;
firstLeast=array[i - 1];
}
if( count > firstLeastCount && count<secondLeastCount)
{
secondLeastCount = count;
secondLeast=array[i - 1];
}
count = 1;
}
else
{
count++;
}
if( i == array.length - 1 )
{
if( firstLeastCount > count )
{
firstLeastCount = count;
firstLeast=array[i - 1];
}
if( count > firstLeastCount && count<secondLeastCount)
{
secondLeastCount = count;
secondLeast=array[i - 1];
}
System.out.println( array[i] + "=" + count );
}
}
System.out.println( "First Least count="+firstLeastCount+" Second Least Count="+secondLeastCount );
System.out.println( "First Least="+firstLeast+" Second Least="+secondLeast );
}
}
public class SecondLeastCommonElement
{
public static void main( String[] args )
{
int[] array = { 5, 5, 4, 5, 4, 6, 6, 6, 1, 3, 3, 4, 4, 5, 4,3,3 };
for( int i = 0; i < array.length - 1; i++ )
{
for( int j = i + 1; j < array.length; j++ )
{
if( array[i] > array[j] )
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
int firstLeast = array[0], secondLeast = array[0];
int firstLeastCount = Integer.MAX_VALUE, secondLeastCount = Integer.MAX_VALUE, count = 1;
for( int i = 1; i < array.length; i++ )
{
if( array[i - 1] != array[i] )
{
System.out.println( array[i - 1] + "=" + count );
if( firstLeastCount > count )
{
firstLeastCount = count;
firstLeast=array[i - 1];
}
if( count > firstLeastCount && count<secondLeastCount)
{
secondLeastCount = count;
secondLeast=array[i - 1];
}
count = 1;
}
else
{
count++;
}
if( i == array.length - 1 )
{
if( firstLeastCount > count )
{
firstLeastCount = count;
firstLeast=array[i - 1];
}
if( count > firstLeastCount && count<secondLeastCount)
{
secondLeastCount = count;
secondLeast=array[i - 1];
}
System.out.println( array[i] + "=" + count );
}
}
System.out.println( "First Least count="+firstLeastCount+" Second Least Count="+secondLeastCount );
System.out.println( "First Least="+firstLeast+" Second Least="+secondLeast );
}
}
and
#Language used: Ruby
puts "Enter the array elements seperated by space: "
arr = []
dummy = []
arr = gets.chomp.split(" ")
arr.sort!
dummy = arr.dup
count = []
elements = []
arr.each do |e|
c = arr.count(e)
count.push(c)
elements.push(e)
arr.delete(e)
end
count.sort!
second_least = count[1]
dummy.each do |e|
if dummy.count(e).to_i == second_least
print e
dummy.delete(e)
end
end
def countFreq(aList):
nFreq = dict()
for a in aList:
if a in nFreq:
nFreq[a] += 1
else:
nFreq[a] = 1
print(aList)
print(nFreq)
lS = sorted(nFreq.items(), key = lambda x: x[1])
print(lS)
leastCommon = lS[0][1]
for x in lS[1:]:
if x[1] > leastCommon:
print('Second Least Common:: ', x[0])
break
l = [1, 3, 5 ,2, 2, 1, 1, 4 ,4, 5, 4, 4 , 7, 3, 2, 1, 4, 5, 2]
countFreq(l)
#include<iostream>
#include<map>
using namespace std;
void pop_arr(int *ptr, int n)
{
cout << " Populate the numbers " << endl;
for(int i=0; i<n; i++)
{
cout << " Enter " << i << "th element : " << endl;
cin >> ptr[i];
}
}
void display(map<int, int> &m)
{
map<int, int> :: iterator it;
for(it = m.begin(); it != m.end(); it++)
cout << " Key : " << (*it).first << " frequency " << (*it).second << endl;
}
int main()
{
int n=0;
cout << " Enter the total number of numbers : " << endl;
cin >> n;
int *ptr = new int[n];
pop_arr(ptr,n);
map<int, int> map_occur;
for(int i=0; i<n; i++)
map_occur[ptr[i] ]++;
display(map_occur);
multimap<int, int> map_occur2;
map<int, int> :: iterator it;
for(it = map_occur.begin(); it != map_occur.end(); it++)
map_occur2.insert(make_pair((*it).second, (*it).first) );
multimap<int, int> :: iterator mit = map_occur2.begin();
int min_num = (*mit).first;
for(mit = map_occur2.begin(); (*mit).first == min_num; mit++)
cout << " Key : " << (*mit).first << " frequency " << (*mit).second << endl;
cout << " Number occuring second least time : " << (*mit).second << endl;
return 0;
}
private int GetSecondLeastMin()
{
int[] a = new int[] { 6, 4, 7, 3, 6, 3, 2, 7, 4, 6, 3, 4, 5 };
int firstMin, secondMin;
if (a[0] <= a[1])
{
firstMin = a[0];
secondMin = a[1];
}
else
{
firstMin = a[1];
secondMin = a[0];
}
for (int i = 2; i < a.Length; i++)
{
if (a[i] < secondMin)
{
if (a[i] < firstMin)
{
int temp = firstMin;
firstMin = a[i];
secondMin = temp;
}
else
{
secondMin = a[i];
}
}
}
return secondMin;
}
I think no need to use hashtable or any other collection, sorting array integer in ascending order will do the trick
int[] arr = { 2,1,1,1,1,1,1,1,1,1,1,1 };
Arrays.sort(arr);
for(int i=0; i<arr.length; i++) {
if(i!= arr.length - 1 && arr[i] != arr[i+1]) {
System.out.println("second least :: "+arr[i+1]);
break;
}
}
Integer[] arr = {5,5,4,5,4,6,6,6,6,6,1,1,1,1,1,1,3,3,4,4,5,4, 88, 88, 88, 88, 88};
int x = Arrays.asList(arr).stream().collect(Collectors.toMap(i->i, i->1, (oldValue, newValue) -> oldValue+1)).entrySet().stream().sorted((k1, k2) -> k1.getValue() - k2.getValue()).collect(Collectors.toList()).get(1).getKey();
System.out.println(x);
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the size of the array");
int n = in.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter " + i + " element");
a[i] = in.nextInt();
}
Arrays.sort(a);
int c=0,c1=0,k=0;
for(int i=0;i<n-1;i++)
{
if(a[i]!=a[i+1])
{
c++;
}
}
c++;
int[] b = new int[c];
for(int i=0;i<n-1;i++)
{
if(a[i]!=a[i+1])
{
b[k]=a[i];
k++;
}
}
b[c-1]=a[n-1];
k=0;
int[] d = new int[c];
for(int i=0;i<n;i++)
{
if(b[k]==a[i])
{
c1++;
}
else
{
d[k] = c1;
c1=1;
k++;
}
}
if(a[n-1]!=a[n-2])
{
d[c-1]=1;
}
else
{
d[c-1]=c1;
}
/*for(int q:d)
{
System.out.print(q+" ");
}*/
int[] e = new int[c];
k=0;
for(int q:d)
{
e[k]=q;
k++;
}
Arrays.sort(e);
for(int i=0;i<c;i++)
{
if(e[i]!=e[i+1])
{
c1 = e[i+1];
break;
}
}
System.out.println();
for(int i=0;i<c;i++)
{
if(d[i]==c1)
{
System.out.println(b[i]);
}
}
}
}
This can be done using time complexity of O(n) and space complexity of O(n). The pretty straight forward way to do this is to use a map(C++) or Hash table(Java) wherein you have to store the frequency of each number.Traverse the map once to get the second least element.
public static int findKthSmallestElement(int[] nums,int k){
//find occurances
Map<Integer,Integer> map = new HashMap<>();
for (int num: nums){
if(map.get(num)!=null) map.put(num,map.get(num)+1);
else map.put(num,1);
}
//Reverse Map in sorted order values<->key
TreeMap<Integer,Integer> sortedMap = new TreeMap<>();
for (Map.Entry<Integer,Integer> entry : map.entrySet()) sortedMap.put(entry.getValue(),entry.getKey());
//find kth element
for (int key :sortedMap.keySet()) if(--k==0) return sortedMap.get(key);
return Integer.MIN_VALUE;
}
- NoOne October 07, 2016