Facebook Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
public void test() {
int[] items = { 11, 30, 2, 30, 30, 30, 6, 2, 62, 62 };
List<Integer> maxIndexes = new ArrayList<Integer>();
int max = 0;
for (int i = 0; i < items.length; i++) {
int maxIndex = 0;
if (items[i] > max) {
maxIndexes.clear();
maxIndexes.add(i);
max = items[i];
} else if (items[i] == max) {
maxIndexes.add(i);
}
System.out.println(maxIndexes.get(new Random().nextInt(maxIndexes
.size())));
}
}
/*
In the current form, the question is ill posed.
It is as good as asking, given an array, find which indices
the maximal elements are - and return one at random.
More realistic and proper question would be:
Given a stream of integers, at any given time, if we were to ask
Give me a random index where the maximal element has appeared.
That would be worth interesting effort.
So we start.
*/
def bucket : { val : num('-inf'), indices : list(-1), cur_index : -1 }
def find_random_index( integer_iterator , bucket ){
if ( integer_iterator.hasNext ){
bucket.cur_index += 1
next_int = integer_iterator.next()
if ( next_int > bucket.val ){
bucket.val = next_int
bucket.indices = list( bucket.cur_index )
} else if ( next_int == bucket.val ){
bucket.indices += bucket.cur_index
}
}
random( bucket.indices ) // return a random value from collection
}
Javascript solution
const findRadomMatchingIndex = arr => {
const matchesMap = {};
let max = Number.MIN_VALUE;
arr.forEach((el, idx) => {
if (el > max) {
max = el;
}
matchesMap[el] ? matchesMap[el].push(idx) : matchesMap[el] = [idx];
});
return matchesMap[max][Math.floor(Math.random() * matchesMap[max].length)]
}
Here is my proposal in Python:
from random import randint
def parseArray(a = [11, 30, 2, 30, 30, 30, 6, 2, 62, 62]):
max_value = 0
for i in range(len(a)):
if a[i] > max_value:
max_value = a[i]
max_indexes = []
if a[i] == max_value:
max_indexes.append(i)
print('Seen so far: {}'.format(a[:i+1]))
print('Max: {}'.format(max_value))
print('Max indexes: {}'.format(max_indexes))
print('Random max index: {}'.format(
max_indexes[randint(0, len(max_indexes) - 1)]))
print('')
Here is my proposal in Python:
from random import randint
def parseArray(a = [11, 30, 2, 30, 30, 30, 6, 2, 62, 62]):
max_value = 0
for i in range(len(a)):
if a[i] > max_value:
max_value = a[i]
max_indexes = []
if a[i] == max_value:
max_indexes.append(i)
print('Seen so far: {}'.format(a[:i+1]))
print('Max: {}'.format(max_value))
print('Max indexes: {}'.format(max_indexes))
print('Random max index: {}'.format(
max_indexes[randint(0, len(max_indexes) - 1)]))
print('')
#include <vector>
#include <map>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include "utils.h"
class Solution {
public:
int getMaxValueIndex(std::vector<int> v, int n) {
std::map<int,std::vector<int>> positions;
for (int i = 0; i <= n; ++i) {
positions[v[i]].push_back(i);
}
const auto it = positions.rbegin();
if(it != positions.rend()) {
//std::cout << it->first << " " << it->second << std::endl;
srand (time(NULL));
return it->second[rand() % it->second.size()];
}
return -1;
}
};
// Driver code
// ===========================================
int main()
{
Solution sol;
std::vector<int> input = {11,30,2,30,30,30,6,2,62,62};
int output = sol.getMaxValueIndex(input,5);
std::cout << output << std::endl;
return 0;
}
Here is the pseudo code for this -
max = INT_MAX
maxMap = new Map
holder = list
foreach i in A upto I
if(A[i] >= max)
then
max = A[i]
if(maxMap.containsKey(max)
then
holder = maxMap.get(max)
else
holder = new list
holder.add(i)
maxMap.put(max, holder)
end
maxEntry = map.entrySet().max(e -> e.value)
random = new random(maxEntry.value)
while random exhausted
print random.nextInt()
Time: O(I)
Space: O(n)
Here is the pseudo code for this -
max = INT_MAX
maxMap = new Map
holder = list
foreach i in A upto I
if(A[i] >= max)
then
max = A[i]
if(maxMap.containsKey(max)
then
holder = maxMap.get(max)
else
holder = new list
holder.add(i)
maxMap.put(max, holder)
end
maxEntry = map.entrySet().max(e -> e.value)
random = new random(maxEntry.value)
while random exhausted
print random.nextInt()
Time: O(I)
Space: O(n)
// Given an array of numbers and position to stop, find the max value
// up to the stop. Then randomly return index of the max value.
function randomIndexOfMaxValue(data, pos) {
// Iterate to pos and find the max value
var indexes = []
var max = 0
for (var i = 0; i < Math.min(pos, data.length); i++) {
if (max < data[i]) {
max = data[i]
indexes = [i]
} else if (max == data[i]) {
indexes.push(i)
}
}
// randomly return index of max value
console.debug(indexes)
return indexes[Math.floor(Math.random() * indexes.length)]
}
console.log(randomIndexOfMaxValue([11, 30, 2, 30, 30, 30, 6, 2, 62, 62], 10))
import random
def find_random_Maxindex(arr):
if not arr:
return -1
max_num = arr[0]
indices = [0]
for i in range(1,len(arr)):
if arr[i] > max_num:
max_num = arr[i]
indices = [i]
elif arr[i] == max_num:
indices.append(i)
else:
continue
return random.choice(indices)
print(find_random_Maxindex([11,30,2,30,30,30,6,2]))
print(find_random_Maxindex([]))
"""
import random
def find_random_Maxindex(arr):
if not arr:
return -1
max_num = arr[0]
indices = [0]
for i in range(1,len(arr)):
if arr[i] > max_num:
max_num = arr[i]
indices = [i]
elif arr[i] == max_num:
indices.append(i)
else:
continue
return random.choice(indices)
print(find_random_Maxindex([11,30,2,30,30,30,6,2]))
print(find_random_Maxindex([]))
"""
import random
def find_random_Maxindex(arr):
if not arr:
return -1
max_num = arr[0]
indices = [0]
for i in range(1,len(arr)):
if arr[i] > max_num:
max_num = arr[i]
indices = [i]
elif arr[i] == max_num:
indices.append(i)
else:
continue
return random.choice(indices)
print(find_random_Maxindex([11,30,2,30,30,30,6,2]))
print(find_random_Maxindex([]))
import random
def find_random_Maxindex(arr):
if not arr:
return -1
max_num = arr[0]
indices = [0]
for i in range(1,len(arr)):
if arr[i] > max_num:
max_num = arr[i]
indices = [i]
elif arr[i] == max_num:
indices.append(i)
else:
continue
return random.choice(indices)
print(find_random_Maxindex([11,30,2,30,30,30,6,2]))
print(find_random_Maxindex([]))
{{
import random
def rand_index(arr):
maxe = arr[0]
indexes = [0]
res = [0]
for i, e in enumerate(arr[1:]):
i += 1
if e > maxe:
maxe = e
indexes = [i]
elif e == maxe:
indexes += [i]
res +=[indexes[random.randint(0, len(indexes)-1)]]
return res
def p(a):
return '\t'.join(str(e) for e in a)
print(p([11, 30, 2, 30, 30, 30, 6, 2, 62, 62]))
print(p(rand_index([11, 30, 2, 30, 30, 30, 6, 2, 62, 62])))
}}
Looking for interview experience sharing and mentors?
- acoding167 March 27, 2019Visit A++ Coding Bootcamp at aonecode.com.
Taught by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greed and other advanced algo problems),
and mock interviews.
Our students got offers from Google, Uber, Facebook, Amazon and other top companies after a few weeks of training.
Welcome to email us with any questions. Thanks for reading.