16 Most Important Facebook Coding Interview Questions
16 Most Important Facebook Coding Interview Questions
• The first row of the source matrix will result in the first column of the obtained matrix in the
reverse order
• The second row of the source matrix will result in the second column of the obtained matrix in
the reverse order
.
.
.
• The last row of the source matrix will result in the last column of the obtained matrix in the
reverse order
Any N x N matrix will have floor(N/2) square cycles. For each square cycle, elements in the
corresponding cell will be swapped in the anti-clockwise direction; from top to left, left to bottom,
bottom to the right, and from right to the top.
For achieving the aforementioned we need nothing more than a temporary variable. Here is how to
achieve rotation of an N x N matrix by 90 degrees in the anti-clockwise direction in C++:
#include <bits/stdc++.h>
#define N 4
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;
}
}
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
2: You are given an array with positive numbers. Explain how you will
find the largest subset of the array containing elements that are
Fibonacci numbers.
Answer: A simple approach for finding out the largest subset of an array of positive numbers that
contain Fibonacci numbers is to iterate through all the elements of the array. Then, check for every
number whether it is a Fibonacci number or not. If it then adds it to the result.
Although the aforementioned approach is simple, it isn’t efficient. Following steps can be followed for
devising an efficient way of achieving the same:
#include<bits/stdc++.h>
int a = 0, b = 1;
unordered_set hash;
hash.insert(a);
hash.insert(b);
int c = a + b;
a = b;
b = c;
hash.insert(b);
if (hash.find(arr[i]) != hash.end())
int main()
int arr[] = ;
int n = sizeof(arr)/sizeof(arr[0]);
findFibSubset(arr, n);
return 0;
}
Output:
8 5 2 1 13
3: Suppose you have an integer array and a positive integer k. How will
you count all distinct pairs with a difference equal to k?
Answer: There can be several approaches to achieving the required. We will discuss two of them:
Approach 1 – Considering All Pairs (NOTE: Will not work for an array with duplicates)
This basic approach involves considering all pairs in the integer array one by one and checking
whether their difference is equal to the given positive integer k or not. If yes, then add them to the
result. Following is the implementation of the approach in C++:
#include
int count = 0;
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: "
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:
#include
if (x == arr[mid])
return mid;
if (x > arr[mid])
else
return -1;
int count = 0, i;
sort(arr, arr+n);
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: "
return 0;
}
Output:
Total number of pairs with the given difference is: 2
4: Can you explain how to find the nth term in Count and Say
sequence.
Answer: To begin with, we need to generate all terms from 1 to n. The first two terms are initialized
as 1 and 11. The third term is generated from the second, fourth from the third, and so on. To
generate the next term, we need to scan the previous term.
While scanning the previous term, we need to keep track of the count of all consecutive characters.
For a sequence of the same characters, we will append the count followed by the character to
generate the next term.
Here is the C++ code for finding the nth term in Count and Say sequence:
#include <bits/stdc++.h>
string countnndSay(int n)
if (n == 1) return "1";
if (n == 2) return "11";
str += '$';
int cnt = 1;
if (str[j] != str[j-1])
tmp += str[j-1];
cnt = 1;
else cnt++;
str = tmp;
return str;
int main()
int N = 4;
return 0;
}
Output:
1211
#include<bits/stdc++.h>
int char_count[MAX_CHAR] = ;
int sum = 0;
char_count[str[i]-'A']++;
else
char ch = (char)('A'+i);
while (char_count[i]--)
if (sum > 0)
return res;
int main()
return 0;
}
Output:
AAABDHHIKLLW8
#include<bits/stdc++.h>
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 res = 0;
int s1 = value(str[i]);
int s2 = value(str[i+1]);
{
res = res + s1;
else
i++;
else
i++;
return res;
int main()
cout << "Integer equivalent for the Roman Numeral is: "
return 0;
Output:
Integer equivalent for the Roman Numeral is: 2422
7: Find the count of the smallest subarray of a given array with a sum
greater than the given value x.
Answer: We will use two nested loops for finding the smallest subarray of a given array with a sum
greater than the given value x. While the outer loop will pick a starting element, the inner loop will
consider all elements as the ending element.
Each time the sum of the elements present between the current start and end becomes greater than
the given number x, the result is updated if the present length is smaller than the previous smallest
length.
The approach can be implemented in C++ using the following code:
#include
int min_len = n + 1;
curr_sum += arr[end];
return min_len;
int main()
int arr1[] = ;
int x = 51
int n1 = sizeof(arr1)/sizeof(arr1[0]);
return 0;
Output:
3
8: From the given array, find a subarray that has at least k numbers
and has the largest possible sum.
Answer: We will first compute the maximum sum until every index is covered and store it in an array
named maxSum[]. Next, we will use the sliding window concept of size k. Then we will keep track of
the sum of the current k elements.
For computing the sum of the current window, we need to remove the first element of the previous
window and add the current element. Once we get the sum of the current window, we will add the
maxSum[] of the previous window, if it will be greater than the current maxSum[].
Here is a C++ program for implementing the aforementioned idea:
#include<bits/stdc++.h>
int maxSum[n];
maxSum[0] = a[0];
maxSum[i] = curr_max;
int sum = 0;
sum += a[i];
return result;
int main()
int a[] = ;
int k = 2;
int n = sizeof(a)/sizeof(a[0]);
return 0;
}
Output:
46
The subarray is 22, 24
• Add the next character as the left child of the root (when encountering the ‘?’ symbol)
• Add the next character as the right child of the root (when encountering the ‘.’ symbol)
• Repeat steps 1 and 2 until all elements of the string are traversed
Following is the demonstration of the approach using C++ code:
#include<bits/stdc++.h>
struct Node
char data;
};
new_node->data = Data;
return new_node;
i++;
if(str[i]=='?')
i++;
root->left = convertExpression(str,i);
i++;
root->right = convertExpression(str,i);
return root;
if (!root)
return ;
printTree(root->right);
int main()
int i=0;
printTree(root) ;
return 0;
Output:
abcde
10: Explain various methods for finding all triplets in an array that has
a total sum of 0.
Answer: There can be three different ways in which we can find all triplets in an array with a total
sum of 0. Let’s discuss them in a brief:
Method 1 – The simplest approach will be to run three loops. Each triplet of the array will be checked
whether the sum of their elements is 0 or not. If found, then print the triplets otherwise, print no triplets
found. The time complexity for this approach will be O(n3).
Method 2 – This method makes use of hashing. While iterating through each element arr[i] of the
array, we will find a pair with the sum -arr[i]. The time complexity for this approach will be O(n2).
Method 3 – The third method involves using sorting and will require an extra space. Although the
time complexity of this method will be O(n2), compared to the O(n) auxiliary space required by the
other two methods, this method only requires O(1) auxiliary space. This method works in the following
steps:
#include<bits/stdc++.h>
sort(arr, arr+n);
int l = i + 1;
int r = n - 1;
int x = arr[i];
while (l < r)
if (x + arr[l] + arr[r] == 0)
l++;
r--;
found = true;
l++;
else
r--;
}
if (found == false)
int main()
int arr[] = ;
int n = sizeof(arr)/sizeof(arr[0]);
findTriplets(arr, n);
return 0;
Output:
-43 1 42
-10 0 10
11: Suppose you are given a binary tree. Explain how you will find its
minimum depth?
Answer: The approach to finding the minimum depth of a binary tree involves traversing the given
binary tree. For each node, check if it’s a leaf node:
#include<bits/stdc++.h>
struct Node
int data;
};
if (root == NULL)
return 0;
return 1;
if (!root->left)
return minDepth(root->right) + 1;
if (!root->right)
return minDepth(root->left) + 1;
temp->data = data;
return (temp);
int main()
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 depth of the given binary tree is: 2
12: Please explain how you will convert any integer value between 1
and 3999 into its Roman numeral equivalent.
Answer: Following algorithm will be used for converting any integer value between 1 and 3999 to its
Roman numeral equivalent:
• Compare the given number with base values 1000, 900, 500, 400, 50, 40, 10, 9, 5, 4, and 1 in
the respective order
• The value that will be the closest, smaller or equal, will serve as the initial base value
• Now, divide the given number with the initial base value
• The corresponding Roman Symbol for the initial base value will be repeated quotient times,
while the remainder will follow Step 1
• The process will be iterated until the remainder becomes 0
c[i++] = num1;
c[i++] = num2;
return i;
c[i++] = ch;
return i;
char c[10001];
int i = 0;
if (number <= 0)
printf("Invalid number");
return;
while (number != 0)
number = number%1000;
else
number = number%100 ;
number = number%100;
else
i = sub_digit('C','D',i,c);
number = number%100;
i = digit('L', number/50,i,c);
number = number%50;
else
i = sub_digit('X','C',i,c);
number = number%10;
i = digit('X', number/10,i,c);
number = number%10;
else
i = sub_digit('X','L',i,c);
number = number%10;
if (number < 9)
i = digit('V', number/5,i,c);
number = number%5;
else
i = sub_digit('I','X',i,c);
number = 0;
if (number < 4)
i = digit('I', number,i,c);
number = 0;
else
printf("The Roman Numeral equivalent for the given number is: ");
printf("%c", c[j]);
int main()
printRoman(number);
return 0;
Output:
The Roman Numeral equivalent to the given number is: MMCDXXII
13: How will you check whether the given string is K-Palindrome or
not?
Answer: We will start with finding the longest palindromic subsequence of the given string. If the
difference between the aforementioned and the given string is less than or equal to k, then the given
string will be k-palindrome, otherwise, it will not be.
We can use the following C++ program to check whether a given string is K-Palindrome or not:
#include <bits/stdc++.h>
if (i == 0 || j == 0)
L[i][j] = 0;
else
return L[m][n];
int n = str.length();
reverse(revStr.begin(), revStr.end());
int main()
int k = 3;
return 0;
Output:
Yes
14: Could you explain how to multiply large numbers represented as
strings?
Answer: We will start by multiplying the last digit of the second number with the first number, followed
by multiplying the second last digit of the second number with the first number, and adding the two.
The process will continue until all digits of the second number are done.
Here’s how to achieve the same in C++:
#include<bits/stdc++.h>
int n1 = num1.size();
int n2 = num2.size();
if (n1 == 0 || n2 == 0)
return "0";
int i_n1 = 0;
int i_n2 = 0;
int carry = 0;
i_n2 = 0;
carry = sum/10;
i_n2++;
if (carry > 0)
i_n1++;
int i = result.size() - 1;
i--;
if (i == -1)
return "0";
string s = "";
while (i >= 0)
s += std::to_string(result[i--]);
return s;
int main()
cout<<"-";
str1 = str1.substr(1);
str2 = str2.substr(1);
str1 = str1.substr(1);
str2 = str2.substr(1);
return 0;
Output:
2375360932037220733184397148506
15: How will you check that the sum of 2 elements in an array equal to
the given number x?
Answer: We can use the following algorithm for checking whether the sum of 2 elements in an array
equals the given number x or not:
#include <bits/stdc++.h>
int l, r;
sort(A, A + arr_size);
l = 0;
r = arr_size - 1;
while (l < r)
return 1;
l++;
r--;
return 0;
int main()
int A[] = ;
int x = 32;
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!
16: 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;
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 goes to stream -> median 10 (5, 15)
1 goes to stream -> median 5 (5, 15, 1)
3 goes to stream -> median 4 (5, 15, 1, 3)
Conclusion
That sums up the list of the most important Facebook Coding interview questions. Hope these
questions will help you crack your upcoming Facebook interview.