YouTube Icon

Interview Questions.

Facebook Interview Questions and Answers - Sep 08, 2021

fluid

Facebook Interview Questions and Answers

Facebook is a social media website organisation founded by using Mark Zuckerberg together with fellow Harvard College college students and roommates Eduardo Saverin, Andrew McCollum, Dustin Moskovitz and Chris Hughes in 2004. Facebook is a business enterprise wherein anyone desires to work in because it works quality perks for the personnel and an amazing enjoy for its personnel. 

Cracking a Facebook interview can be a hard pill to swallow. However, with a decent technical coaching and a groovy head, you may benefit a operating possibility at the sector’s biggest social media massive.

Facebook Interview Questions and Answers

Typically, a Facebook interview technique involves:

2 telephonic rounds – Focuses on fundamental hassle fixing and statistics structures

2 or three coding on-web site rounds – Involves whiteboarding solutions for slightly above average statistics structures/algorithmic issues. More rounds for the lesser experienced

1 or 2 device layout on-web page rounds – Aims at gauging the ability of the interviewee in coming up with efficient high-level layout architectures for real-existence products. The extra skilled candidates will face extra of those rounds

1 cultural in shape on-website round – Meant for comparing whether the interviewee can be an amazing cultural match for Facebook or not. Doesn’t require any technical knowledge

While the telephonic rounds will contain thinking approximately facts structures and hassle-solving, device layout is supposed for just a few applicants. So, that leaves with the on-web site coding rounds, which can be the maximum vital.

Here are 16 most vital Facebook interview questions that you can anticipate coming your manner in the coding on-website rounds:

Question: How will you rotate a square (N x N) matrix by means of ninety stages within the anti-clockwise path with out using any greater area?

Answer: Suppose we've got the following matrix:

1 2 three

4 5 6

7 8 9

Then, rotating it through ninety ranges inside the anti-clockwise direction will result in the following matrix:

three 6 nine

2 five 8

1 four 7

Following deductions can be made after inspecting the aforementioned resultant matrix:

The first row of the supply matrix will bring about the primary column of the acquired matrix within the opposite order

The second row of the supply matrix will bring about the second one column of the received matrix in the reverse order

.

.

.

The remaining row of the supply matrix will bring about the last column of the obtained matrix inside the reverse order

Any N x N matrix may have floor(N/2) square cycles. For each square cycle, factors in the corresponding cell will be swapped inside the anti-clockwise course; from top to left, left to bottom, backside to the proper, and from right to the pinnacle.

For accomplishing the aforementioned we want nothing more than a brief variable. Here is a way to attain rotation of an N x N matrix by 90 stages within the anti-clockwise path in C++:

#include <bits/stdc++.h>
#define N 4
using namespace std;
void displayMatrix(int mat[N][N]);
void rotateMatrix(int mat[][N])
{
 for (int x = 0; x < N / 2; x++) 
 {
 for (int y = x; y < N-x-1; y++) 
 { 
 int temp = mat[x][y]; 
 mat[x][y] = mat[y][N-1-x]; 
 mat[y][N-1-x] = mat[N-1-x][N-1-y]; 
 mat[N-1-x][N-1-y] = mat[N-1-y][x]; 
 mat[N-1-y][x] = temp; 
 } 
 } 
}
void displayMatrix(int mat[N][N]) 
{ 
 for (int i = 0; i < N; i++) 
 { 
 for (int j = 0; j < N; j++) 
 printf("%2d ", mat[i][j]);
 printf("\n"); 
 } 
 printf("\n"); 
} 
int main() 
{ 
 int mat[N][N] = 
 { 
 , 
 , 
 , 
 
 }; 
 rotateMatrix(mat); 
 displayMatrix(mat); 
 return 0; 
}

Output:

4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

Question: You are given an array with high-quality numbers. Explain how you will find the biggest subset of the array containing elements which can be Fibonacci numbers.

Answer: A easy method for locating out the largest subset of an array of superb numbers that contain Fibonacci numbers is to iterate via all of the factors of the array. Then, check for every variety whether or not it's miles a Fibonacci range or no longer. If it then adds it to the end result.

Although the aforementioned method is easy, it isn’t green. Following steps can be observed for devising an efficient way of reaching the identical:

Find the max within the array

Generate Fibonacci numbers until the max of the array and save the same in a hash desk

Traverse the array again and add all numbers present in the array and the hash desk to the result

Following C++ code demonstrates an powerful solution:

#include<bits/stdc++.h>
using namespace std;
void findFibSubset(int arr[], int n)
{
int max = *std::max_element(arr, arr+n);
int a = 0, b = 1;
unordered_set hash;
hash.insert(a);
hash.insert(b);
while (b < max)
{
int c = a + b;
a = b;
b = c;
hash.insert(b);
}
for (int i=0; i<n; i++)
if (hash.find(arr[i]) != hash.end())
printf("%d ", arr[i]);
}
int main()
{
int arr[] = ;
int n = sizeof(arr)/sizeof(arr[0]);
findFibSubset(arr, n);
return 0;
}

Output:

8 five 2 1 13

Question: Suppose you have an integer array and a fine integer ok. How will you remember all wonderful pairs with a distinction same to ok?

Answer: There may be several procedures to accomplishing the specified. We will talk two of them:

Approach 1 – Considering All Pairs (NOTE: Will no longer work for an array with duplicates)

This simple method includes considering all pairs within the integer array one by one and checking whether their distinction is identical to the given positive integer k or now not. If yes, then add them to the result. Following is the implementation of the method in C++:

#include 
using namespace std; 
int countPairsWithDiffK(int arr[], int n, int k) 
{ 
 int count = 0; 
 for (int i = 0; i < n; i++) 
 { 
 for (int j = i+1; j < n; j++) 
 if (arr[i] - arr[j] == k || arr[j] - arr[i] == k ) 
 count++; 
 } 
 return count; 
} 
 
int main() 
{ 
 int arr[] = ; 
 int n = sizeof(arr)/sizeof(arr[0]); 
 int k = 3;
 cout << "Total number of pairs with the given difference is: "
 << countPairsWithDiffK(arr, n, k); 
 return 0;
}

Output:

Total number of pairs with the given difference is: 2

Approach 2 – Using Sorting

Another approach of finding the pair count is by using an O(nLogn) sorting algorithm, such as Heap Sort and Merge Sort. Following steps describe the approach:

Initialize the count to 0

Sort the array elements in increasing order

Eliminate duplicates from the array (if any)

For each element arr[i]:

Binary Search for arr[i] + k in the subarray from i+1 to n-1

If arr[i] + k is found, increment the count

Return count

Here is the C++ code for implementing the aforementioned approach:

#include 
#include 
using namespace std;
int binarySearch(int arr[], int low, int high, int x)
{
if (high >= low)
{
int mid = low + (high - low)/2;
if (x == arr[mid])
return mid;
if (x > arr[mid])
return binarySearch(arr, (mid + 1), high, x);
else
return binarySearch(arr, low, (mid -1), x);
}
return -1;
}
int countPairsWithDiffK(int arr[], int n, int k)
{
int count = 0, i;
sort(arr, arr+n);
for (i = 0; i < n-1; i++)
if (binarySearch(arr, i+1, n-1, arr[i] + k) != -1)
count++;
return count;
}
int main()
{
int arr[] = ;
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
cout << "Total number of pairs with the given difference is: "
<< countPairsWithDiffK(arr, n, k);
return 0;
}

Output:

Total wide variety of pairs with the given difference is: 2

Question: Can you provide an explanation for a way to discover the nth term in Count and Say series.

Answer: To start with, we need to generate all terms from 1 to n. The first two terms are initialized as 1 and eleven. The 1/3 term is generated from the second one, fourth from the 1/3, and so forth. To generate the subsequent term, we want to experiment the previous time period.

While scanning the preceding time period, we want to keep track of the matter of all consecutive characters. For a chain of the equal characters, we will append the rely followed by using the character to generate the subsequent term.

Here is the C++ code for finding the nth term in Count and Say sequence:

#include <bits/stdc++.h>
using namespace std;
string countnndSay(int n)
{
if (n == 1) return "1";
if (n == 2) return "11";
string str = "11";
for (int i = 3; i<=n; i++)
{
str += '$';
int len = str.length();
int cnt = 1;
string tmp = "";
for (int j = 1; j < len; j++)
{
if (str[j] != str[j-1])
{
tmp += cnt + '0';
tmp += str[j-1];
cnt = 1;
}
else cnt++;
}
str = tmp;
}
return str;
}
int main()
{
int N = 4;
cout << countnndSay(N) << endl;
return 0;
}

Output:

1211

Question: If you're given a string containing uppercase alphabets and integers, how are you going to print the string with alphabets following the lexicographic order accompanied by using the sum of the integers?

Answer: Here is the step-via-step description of a way to attain the favored:

Traverse the given string

(For an alphabet) Increment its occurrence matter into a hash table

(For an integer) Store it one after the other and add it to the preceding sum

Use a hash desk to append all the alphabets first right into a string following lexicographic order after which append the sum of the integers on the give up

Return the consequent string

Following code demonstrates implementing the output in C++:

#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
string arrangeString(string str)
{
int char_count[MAX_CHAR] = ;
int sum = 0;
for (int i = 0; i < str.length(); i++)
{
if (str[i]>='A' && str[i] <='Z')
char_count[str[i]-'A']++;
else
sum = sum + (str[i]-'0');
}
string res = "";
for (int i = 0; i < MAX_CHAR; i++)
{
char ch = (char)('A'+i);
while (char_count[i]--)
res = res + ch;
}
if (sum > 0)
res = res + to_string(sum);
return res;
}
int main()
{
string str = "AKHIL20BHADWAL24";
cout << arrangeString(str);
return 0;
}

Output:

AAABDHHIKLLW8

Question: Convert a roman numeral into its corresponding integer variety.

Answer: We will use the subsequent set of rules for converting Roman Numerals into the equivalent integer number:

Split the available Roman Numeral string into Roman Symbols

Convert every Roman Symbol into its equivalent integer fee

For each symbol, beginning from index zero:

(If the cutting-edge fee of the Roman Symbol is more than or identical to the price of the subsequent Roman Symbol) Add this fee to the whole

(If the modern-day price of the Roman Symbol is less than the cost of the subsequent Roman Symbol) Subtract this value by means of adding the price of the next symbol to the full

Following C++ code demonstrates the algorithm:

#include<bits/stdc++.h>
using namespace std;
int value(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
int romanToDecimal(string &str)
{
int res = 0;
for (int i=0; i<str.length(); i++)
{
int s1 = value(str[i]);
if (i+1 < str.length())
{
int s2 = value(str[i+1]);
if (s1 >= s2)
{
res = res + s1;
}
else
{
res = res + s2 - s1;
i++;
}
}
else
{
res = res + s1;
i++;
}
}
return res;
}
int main()
{
string str ="MMCDXXII";
cout << "Integer equivalent for the Roman Numeral is: "
<< romanToDecimal(str) << endl;
return 0;
}

Output:

Integer equal for the Roman Numeral is: 2422

Question: Find the count of the smallest subarray of a given array with a sum greater than the given cost x.

Answer: We will use two nested loops for finding the smallest subarray of a given array with a sum greater than the given price x. While the outer loop will pick a starting detail, the inner loop will consider all elements as the ending detail.

Each time the sum of the factors present between the modern-day start and stop will become more than the given range x, the end result is up to date if the prevailing period is smaller than the preceding smallest period.

The approach can be applied in C++ the use of the following code:

#include 
using namespace std;
int smallestSubWithSum(int arr[], int n, int x)
{
int min_len = n + 1;
for (int start=0; start<n; start++)
{
int curr_sum = arr[start];
if (curr_sum > x) return 1;
for (int end=start+1; end<n; end++)
{
curr_sum += arr[end];
if (curr_sum > x && (end - start + 1) < min_len)
min_len = (end - start + 1);
}
}
return min_len;
}
int main()
{
int arr1[] = ;
int x = 51
int n1 = sizeof(arr1)/sizeof(arr1[0]);
int res1 = smallestSubWithSum(arr1, n1, x);
(res1 == n1+1)? cout << "Not possible\n" :
cout << res1 << endl;
return 0;
}

Output:

3

Question: From the given array, find a subarray that has as a minimum k numbers and has the most important viable sum.

Answer: We will first compute the most sum till each index is blanketed and shop it in an array named maxSum[]. Next, we are able to use the sliding window concept of size okay. Then we can hold track of the sum of the current k factors.

For computing the sum of the contemporary window, we want to put off the primary detail of the previous window and add the cutting-edge element. Once we get the sum of the contemporary window, we can add the maxSum[] of the preceding window, if it will be extra than the modern-day maxSum[].

Here is a C++ application for implementing the aforementioned concept:

#include<bits/stdc++.h>
using namespace std;
int maxSumWithK(int a[], int n, int k)
{
int maxSum[n];
maxSum[0] = a[0];
int curr_max = a[0];
for (int i = 1; i < n; i++)
{
curr_max = max(a[i], curr_max+a[i]);
maxSum[i] = curr_max;
}
int sum = 0;
for (int i = 0; i < k; i++)
sum += a[i];
int result = sum;
for (int i = k; i < n; i++)
{
sum = sum + a[i] - a[i-k];
result = max(result, sum);
result = max(result, sum + maxSum[i-k]);
}
return result;
}
int main()
{
int a[] = ;
int k = 2;
int n = sizeof(a)/sizeof(a[0]);
cout << maxSumWithK(a, n, k);
return 0;
}

Output:

forty six

The subarray is 22, 24

Question: How will you change a ternary expression to a binary tree?

Answer: We will start with traversing the string, making the first person as the foundation after which:

Add the subsequent individual as the left infant of the root (when encountering the ‘?’ image)

Add the subsequent man or woman as the right infant of the foundation (while encountering the ‘.’ image)

Repeat steps 1 and a pair of till all elements of the string are traversed

Following is the demonstration of the technique using C++ code:

#include<bits/stdc++.h>
using namespace std;
struct Node
{
char data;
Node *left, *right;
};
Node *newNode(char Data)
{
Node *new_node = new Node;
new_node->data = Data;
new_node->left = new_node->right = NULL;
return new_node;
}
Node *convertExpression(string str, int & i)
{
Node * root =newNode(str[i]);
if(i==str.length()-1) return root;
i++;
if(str[i]=='?')
{
i++;
root->left = convertExpression(str,i);
i++;
root->right = convertExpression(str,i);
return root;
}
else return root;
}
void printTree( Node *root)
{
if (!root)
return ;
cout << root->data <<" ";
printTree(root->left);
printTree(root->right);
}
int main()
{
string expression = "a?b?c:d:e";
int i=0;
Node *root = convertExpression(expression, i);
printTree(root) ;
return 0;
}

Output:

a b c d e

Question: Explain various methods for locating all triplets in an array that has a complete sum of 0.

Answer: There may be three unique ways in which we will discover all triplets in an array with a total sum of 0. Let’s speak them in a short:

Method 1 – The most effective approach will be to run 3 loops. Each triplet of the array will be checked whether or not the sum of their elements is zero or now not. If discovered, then print the triplets in any other case, print no triplets found. The time complexity for this approach will be O(n3).

Method 2 – This approach makes use of hashing. While iterating thru every element arr[i] of the array, we can discover a pair with the sum -arr[i]. The time complexity for this technique may be O(n2).

Method 3 – The 1/3 technique entails using sorting and will require an extra space. Although the time complexity of this technique might be O(n2), compared to the O(n) auxiliary space required through the alternative two strategies, this approach best calls for O(1) auxiliary area. This technique works inside the following steps:

Sort all factors of the given array

Run loop from i=zero to n-2

Initialize  index variable l = i+1 and r = n-1

While (l<r), check the sum of arr[i], arr[l], and arr[r] then:

If the sum is much less than 0 then l++

If the sum is extra than 0 then r--

If the sum is zero then print the triplet and do l++ and r--

Following C++ program implements Method three:

#include<bits/stdc++.h>
using namespace std;
void findTriplets(int arr[], int n)
{
bool found = false;
sort(arr, arr+n);
for (int i=0; i<n-1; i++)
{
int l = i + 1;
int r = n - 1;
int x = arr[i];
while (l < r)
{
if (x + arr[l] + arr[r] == 0)
{
printf("%d %d %d\n", x, arr[l], arr[r]);
l++;
r--;
found = true;
}
else if (x + arr[l] + arr[r] < 0)
l++;
else
r--;
}
}
if (found == false)
cout << " Not found!" << endl;
}
int main()
{
int arr[] = ;
int n = sizeof(arr)/sizeof(arr[0]);
findTriplets(arr, n);
return 0;
}

Output:

-43 1 42

-10 zero 10

Question: Suppose you are given a binary tree. Explain how you may find its minimal depth?

Answer: The technique to finding the minimum intensity of a binary tree includes traversing the given binary tree. For every node, check if it’s a leaf node:

If yes, then go back 1

If no, then:

Recur for the right subtree if the left subtree is NULL

Recur for the left subtree if the proper subtree is NULL

Take the minimum of the two depths if each the left and proper subtrees are not NULL

Here is an implementation of the aforementioned approach using C++ code:

#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
};
int minDepth(Node *root)
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;
if (!root->left)
return minDepth(root->right) + 1;
if (!root->right)
return minDepth(root->left) + 1;
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
Node *newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return (temp);
}
int main()
{
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->left->left = newNode(6);
root->left->left->right = newNode(7);
cout <<"The minimum depth of the given binary tree is: "<< minDepth(root);
return 0;
}

Output:

The minimum intensity of the given binary tree is: 2

Question: Please provide an explanation for how you'll convert any integer price between 1 and 3999 into its Roman numeral equivalent.

Answer: Following set of rules might be used for changing any integer value between 1 and 3999 to its Roman numeral equivalent:

Compare the given number with base values a thousand, 900, 500, four hundred, 50, forty, 10, 9, five, four, and 1 within the respective order

The fee on the way to be the nearest, smaller or equal, will serve as the initial base price

Now, divide the given quantity with the preliminary base value

The corresponding Roman Symbol for the preliminary base fee could be repeated quotient times, whilst the the rest will observe Step 1

The process might be iterated till the the rest will become 0

The set of rules can be applied in C++ the use of the subsequent code:

#include <bits/stdc++.h>
using namespace std;
int sub_digit(char num1, char num2, int i, char *c)
{
c[i++] = num1;
c[i++] = num2;
return i;
}
int digit(char ch, int n, int i, char *c)
{
for (int j = 0; j < n; j++)
c[i++] = ch;
return i;
}
void printRoman(int number)
{
char c[10001];
int i = 0;
if (number <= 0)
{
printf("Invalid number");
return;
}
while (number != 0)
{
if (number >= 1000)
{
i = digit('M', number/1000, i, c);
number = number%1000;
}
else if (number >= 500)
{
if (number < 900)
{
i = digit('D', number/500, i, c);
number = number%500;
}
else
{
i = sub_digit('C', 'M', i, c);
number = number%100 ;
}
}
else if (number >= 100)
{
if (number < 400)
{
i = digit('C', number/100, i, c);
number = number%100;
}
else
{
i = sub_digit('C','D',i,c);
number = number%100;
}
}
else if (number >= 50 )
{
if (number < 90)
{
i = digit('L', number/50,i,c);
number = number%50;
}
else
{
i = sub_digit('X','C',i,c);
number = number%10;
}
}
else if (number >= 10)
{
if (number < 40)
{
i = digit('X', number/10,i,c);
number = number%10;
}
else
{
i = sub_digit('X','L',i,c);
number = number%10;
}
}
else if (number >= 5)
{
if (number < 9)
{
i = digit('V', number/5,i,c);
number = number%5;
}
else
{
i = sub_digit('I','X',i,c);
number = 0;
}
}
else if (number >= 1)
{
if (number < 4)
{
i = digit('I', number,i,c);
number = 0;
}
else
{
i = sub_digit('I', 'V', i, c);
number = 0;
}
}
}
printf("The Roman Numeral equivalent for the given number is: ");
for (int j = 0; j < i; j++)
printf("%c", c[j]);
}
int main()
{
int number = 2422;
printRoman(number);
return 0;
}

Output:

The Roman Numeral equivalent to the given variety is: MMCDXXII

Question: How will you test whether or not the given string is K-Palindrome or no longer?

Answer: We will begin with locating the longest palindromic subsequence of the given string. If the difference between the aforementioned and the given string is much less than or same to ok, then the given string could be k-palindrome, in any other case, it'll not be.

We can use the following C++ application to test whether a given string is K-Palindrome or not:

#include <bits/stdc++.h>
using namespace std;
int lcs( string X, string Y, int m, int n )
{
int L[m + 1][n + 1];
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
}
}
return L[m][n];
}
bool isKPal(string str, int k)
{
int n = str.length();
string revStr = str;
reverse(revStr.begin(), revStr.end());
int lps = lcs(str, revStr, n, n);
return (n - lps <= k);
}
int main()
{
string str = "abvcdeca";
int k = 3;
isKPal(str, k) ? cout << "Yes" : cout << "No";
return 0;
}

Output:

Yes

Question: Could you explain a way to multiply large numbers represented as strings?

Answer: We will begin via multiplying the last digit of the second wide variety with the primary variety, accompanied by means of multiplying the second one ultimate digit of the second range with the first quantity, and including the two. The technique will retain till all digits of the second number are performed.

Here’s a way to reap the equal in C++:

#include<bits/stdc++.h>
using namespace std;
string multiply(string num1, string num2)
{
int n1 = num1.size();
int n2 = num2.size();
if (n1 == 0 || n2 == 0)
return "0";
vector result(n1 + n2, 0);
int i_n1 = 0;
int i_n2 = 0;
for (int i=n1-1; i>=0; i--)
{
int carry = 0;
int n1 = num1[i] - '0';
i_n2 = 0;
for (int j=n2-1; j>=0; j--)
{
int n2 = num2[j] - '0';
int sum = n1*n2 + result[i_n1 + i_n2] + carry;
carry = sum/10;
result[i_n1 + i_n2] = sum % 10;
i_n2++;
}
if (carry > 0)
result[i_n1 + i_n2] += carry;
i_n1++;
}
int i = result.size() - 1;
while (i>=0 && result[i] == 0)
i--;
if (i == -1)
return "0";
string s = "";
while (i >= 0)
s += std::to_string(result[i--]);
return s;
}
int main()
{
string str1 = "24224620578";
string str2 = "98055650629857338077";
if((str1.at(0) == '-' || str2.at(0) == '-') &&
(str1.at(0) != '-' || str2.at(0) != '-' ))
cout<<"-";
if(str1.at(0) == '-' && str2.at(0)!='-')
{
str1 = str1.substr(1);
}
else if(str1.at(0) != '-' && str2.at(0) == '-')
{
str2 = str2.substr(1);
}
else if(str1.at(0) == '-' && str2.at(0) == '-')
{
str1 = str1.substr(1);
str2 = str2.substr(1);
}
cout << multiply(str1, str2);
return 0;
}

Output:

2375360932037220733184397148506

Question: How will you test that the sum of two elements in an array equal to the given quantity x?

Answer: We can use the following set of rules for checking whether the sum of 2 factors in an array equals the given range x or not:

Sort the given array in decreasing order

Initialize two index variables:

l = zero to the leftmost index

r = ar_size-1 to the rightmost index

While l<r:

Return 1, if A[l] + A[r] == sum

l++, if A[l] + A[r] < sum

Otherwise r--

Continue looping step 3 until all factors within the array are exhausted

Here is a C++ program demonstrating the aforementioned approach:

#include <bits/stdc++.h>
using namespace std;
bool hasArrayTwoCandidates(int A[], int arr_size, int sum)
{
int l, r;
sort(A, A + arr_size);
l = 0;
r = arr_size - 1;
while (l < r)
{
if(A[l] + A[r] == sum)
return 1;
else if(A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return 0;
}
int main()
{
int A[] = ;
int x = 32;
int arr_size = sizeof(A) / sizeof(A[0]);
if (hasArrayTwoCandidates(A, arr_size, n))
cout << "The array has two elements with the given sum!";
else
cout << "The given array doesn't have two elements with the given sum!";
return 0;
}

Output:

The given array has two elements with the given sum!

Question: You are given an input stream of N integers that you need to insert in a new stream. How will you find the median of the new stream formed by each insertion of x to the new stream?

Answer:

The Input - The first line of the input contains an integer N that represents the total number of elements in the stream. Next N lines contain integer x that represents the number to be inserted into the stream.

The Output - For each of the element added to the stream print the floor of the new median in a new line.

For the output to be correct we need to follow two constraints;

N is greater than or equal to 1 and less than or equal to 106

x is greater than or equal to 1 and less than or equal to 106

An example:

Input:

4 (Number of elements i.E. N)

5*

15*

1*

3*

* = The elements of the stream

The output will be:

5

10

5

4

Explanation:

5 goes to stream -> median 5 (5)

15 is going to circulation -> median 10 (five, 15)

1 is going to stream -> median five (5, 15, 1)

three is going to stream -> median four (five, 15, 1, 3)

Conclusion

That sums up the list of the maximum crucial Facebook Coding interview questions. Hope these questions will help you crack your upcoming Facebook interview.

Looking for extra interview questions? This is an outstanding udemy direction which could put together you for programming interviews: Break Away: Programming And Coding Interviews.

Here is a terrific e book with pinnacle well-known coding questions and solutions to help along with your practise: Cracking the Coding Interview: 189 Programming Questions and Solutions.

All the quality!




CFG