Facebook Interview Question for Software Engineers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
0
of 2 vote

public void sampleIdx(int[] array){
        if(array == null || array.length == 0){
            return;
        }
        Random rnd = new Random();
        int res = 0, max = Integer.MIN_VALUE, count = 0;
        for(int i = 0; i < array.length; i++){
            if(max < array[i]){
            	max = array[i];
                res = i;
                count = 1;
            }else if(max == array[i]){
                count++;
                int idx = rnd.nextInt(count); //(0, k - 1)
                if(idx == 0){

                    res = i;
		        System.out.print(“A max value index up to the ”+i +”th element is ” + res;
);

                }
            }
        }
    }

Looking for interview experience sharing and mentors?
Visit 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.

- acoding167 March 27, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

That shouldn't work because this code doesn't keep previous indexes of max element.

- ArtyomKarpov October 06, 2021 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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())));
}

}

- Bhavin Pandya March 28, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python solution

def get_max(l = [11,30,2,30,30,30,6,2,62]):
	rand = random.randint(0, len(l))
	max_integer = (max(l[:rand]))
	indexes=[]
	for i in range(rand):
		if l[i] == max_integer:
			indexes.append(i)
	print(rand)
	print(max_integer)
	print(indexes)

- pro100Istomin1988 April 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* 
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 
}

- NoOne April 12, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

return list.slice(0, cut + 1).reduce((accumulator, current, index, array) => {
        return (current >= array[accumulator]) ? index : accumulator;
    }, 0);

- rodkammer April 12, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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)]
}

- Vinicius Santana May 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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('')

- littlebigfab May 17, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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('')

- littlebigfab May 17, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#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;
}

- Miniruwan July 19, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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)

- bitsevn August 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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)

- bitsevn August 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// 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))

- sheng August 22, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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([]))

- Anonymous August 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

"""
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([]))
"""

- Anonymous August 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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([]))

- Anonymous August 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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([]))

- Anonymous August 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{

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])))


}}

- ArtyomKarpov October 06, 2021 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More