Facebook Interview Question for Software Engineers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
1
of 1 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 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


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