Amazon Interview Question
Country: United States
Interview Type: Phone Interview
This is a kth order statistics problem can be solved in O(n).
Rand-Select() algorithm works too.
There is a rather special case (since its just second largest) - brute force as below.
namespace QuickPorjects
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 7,1,2,3,4,5,8 };
FindTwoLargest(arr);
}
private static void FindTwoLargest(int[] arr)
{
int max = int.MinValue;
int max_second = int.MinValue;
int i;
//max = arr[0];
for (i = 0; i < arr.Length; i++)
{
if (arr[i] > max)
{
max_second = max;
max = arr[i];
}
else if (arr[i] > max_second)
{
max_second = arr[i];
}
}
Console.WriteLine(max + " " + max_second);
}
}
}
Revised algorithm:
- Iterate the array from left to right and from right to left to find the largest element in each direction.
- When checking for the largest element in this direction, ignore the largest element from the other direction.
- Find the smallest elment in these two largest elements.
int findSecondLargest(int A[], int N)
{
int left = 0;
int right = N - 1;
for (int i = left, j = right; i < N && j >= 0; i++, j--)
{
if (A[left] < A[i] && i != right)
left = i;
if (A[right] < A[j] && j != left)
right = j;
}
if (A[left] < A[right])
return A[left];
else
return A[right];
}
Can you please expand on that?
What betterment are you trying to achieve over this:
int *max, *secondmax;
max = secondmax = NULL;
for( i = 0; i < n; i++ )
{
if( max == NULL )
max = new int(a[i]);
else if( *max < a[i] )
if( secondmax == NULL ) secondmax = new int;
*secondmax = *max;
*max = a[i];
else if( *secondmax < a[i] )
*secondmax = a[i];
}
Build max-heap, remove the root and max heapify again. I guess this should take order n times.
To get the second largest
we can use bubble sort (2 times outer loop... N-2 is second largest element)
Or selection sort method as below.
#include <iostream>
using namespace std;
int main()
{
int a[] = {0,0,0,1,2,0};
int pos,temp;
int n = 6;
for (int i =0; i<2; i++)
{
pos = i;
for(int j= i+1; j<n; j++)
{
if(a[j] > a[pos])
{
pos = j;
}
}
if(pos != i)
{
temp = a[pos];
a[pos] = a[i];
a[i] = temp;
}
}
cout << "Second Largest: "<< a[1] << endl;
}
This is not correct if the second largest element is in the same subarray as the largest one.
This is not correct if the second largest element is in the same subarray as the largest one.
#include "stdafx.h"
- Dinesh March 03, 2012#include <stdio.h>
int main() {
int A[] = {1,2,3,4,5};
int max1 = 0, max2 = 0;
for(int i = 0; i < 5;i++) {
if(A[i] > max1) {
max2 = max1;
max1 = A[i];
}
else if(A[i] > max2 && A[i] < max1) {
max2 = A[i];
}
}
printf("%d\n",max2);
}