Chapter 45 Facebook 2017 Interview Questions Part 1
45.1 273. Integer to English Words
https://leetcode.com/problems/integer-to-english-words/
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than \(2^{31} - 1\).
For example,
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
罗马人发明的罗马数字主要靠加,所以只能表示到3999. 参见: linkedin-before-2015. 印度人发明的阿拉伯数字系统(Arabic Numerals)就有了递归的概念,可以表示任意大的数(所有的有理数). 其实我们在念数字的时候已经运用了recursive function,只是我们自己不知道而已.
所以这题用递归来做.
struct Solution {// 3ms
vector<string> _1_19 = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen","Seventeen", "Eighteen", "Nineteen" };
vector<string> _10_90 = {"Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
string rec(int n) {
if (n >= 1e9) return rec(n / 1e9) + " Billion" + rec(n % (int)1e9);
if (n >= 1e6) return rec(n / 1e6) + " Million" + rec(n % (int)1e6);
if (n >= 1000) return rec(n / 1000) + " Thousand" + rec(n % 1000);
if (n >= 100) return rec(n / 100) + " Hundred" + rec(n % 100);
if (n >= 20) return " " + _10_90[n / 10 - 1] + rec(n % 10);
if (n >= 1) return " " + _1_19[n - 1];
return "";
}
string numberToWords(int num) {
if (num == 0) return "Zero";
string r = rec(num);
r.erase(r.begin()); // Remove space in the beginning
return r;
}
};
Or even simpler:
class Solution {
vector<string> _1_19 = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven","Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
vector<string> _10_90 = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty","Ninety"};
public:
string numberToWords(int num) {
if(num==0) return "Zero";
if(num<20) return _1_19[num-1];
if(num<100) return _10_90[num/10-1] + ((num%10)?(" "+_1_19[num%10-1]):"");
if(num<1e3) return numberToWords(num/100) + " Hundred" + ((num%100)?(" "+numberToWords(num%100)):"");
if(num<1e6) return numberToWords(num/1000) + " Thousand" + ((num%1000)?(" "+numberToWords(num%1000)):"");
if(num<1e9) return numberToWords(num/int(1e6)) + " Million" + ((num%int(1e6))?(" "+numberToWords(num%int(1e6))):"");
return numberToWords(num/int(1e9)) + " Billion" + ((num%int(1e9))?(" "+numberToWords(num%int(1e9))):"");
}
};
45.2 283. Move Zeroes
https://leetcode.com/problems/move-zeroes/
http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=218930
Check: 283. Move Zeroes
45.3 Amazing Numbers
https://www.careercup.com/question?id=6018738030641152
An element in an array is said to be amazing if its value is less than or equal to its index. Given a circular array of numbers, write an efficient algorithm find the starting index that leads to the maximum number of amazing elements. Example:
input array: [3, 0, 1, 0]:
starting index = 0: [3, 0, 1, 0] => number of amazing elements = 3
starting index = 1: [0, 1, 0, 3] => number of amazing elements = 4
starting index = 2: [1, 0, 3, 0] => number of amazing elements = 2
starting index = 3: [0, 3, 0, 1] => number of amazing elements = 3
Therefore the answer will be 1.
Input Format
First line specifies the number of elements N in the input array. This is followed by N lines corresponding to the array elements.
Constraints
None
Output Format
One number that specifies the starting index in the circular array that leads to the maximum number of amazing elements, if there is more than one such indices, choose the smallest index.
http://bit.ly/2wdRAML, http://bit.ly/2wdIks8, http://bit.ly/2wdRHrF
45.3.2 Algo 2: Meeting Rooms II Algorithm
T: \(O(N)\)
int GetAmazingNumber(vector<int> v){
vector<pair<int,int>> vp;
int L=v.size();
for(int i=0;i<L;++i){
if(v[i]>=L) continue;
int start=(i+1) % L, end=(i-v[i]+L) % L;
vp.emplace_back(start, end);
}
vector<int> counter(L); // Range Addition Algorithm
for(auto pr: vp){
counter[pr.first]++;
if(pr.first>pr.second)
counter[0]++;
if(pr.second+1<L)
counter[pr.second+1]--;
}
int mx=counter[0];
int r=0;
for(int i=1;i<L;++i){
counter[i]+=counter[i-1];
if(counter[i]>mx)
r=i, mx=counter[i];
}
return r;
}
Brutal force is trivial: For each index as starting point, count number of amazing number in the array, then update index if we see a max.
There is a clever way of doing it in the original post, which utilizes interval. For any number, if it’s larger than the length of the array, there is no way we can make it an amazing number. Otherwise, starting from the next index of the current one can always make the number an amazing number. The largest index would be length_of_array + current_index - array[current_index]
. This is because current_index - array[current_index]
is the index we need to make the number an amazing number. If the number is larger than current index, this index will become negative, so we need to add length of array to keep the index in the array. For current_index > array[current_index]
, this operation will lead to index > length of array, so we mod the index by length.
After we get all intervals, we need to find the index that all intervals intersects most, which is the index that contains the most amazing numbers. To do that, we can use algorithm in Range Addition or Meeting Room II.
For start > end, we need to split interval to two: [start, len - 1], [0, end]
最后几行用STL可以这样写:
partial_sum(cnt.begin(), cnt.end(), cnt.begin());
return max_element(cnt.begin(), cnt.end())-cnt.begin();
参考: Range Addition
45.4 252. Meeting Rooms
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],…] (si < ei), determine if a person could attend all meetings.
For example, Given [[0, 30],[5, 10],[15, 20]], return false.
https://leetcode.com/problems/meeting-rooms
本题的做法就是先根据初始点sort一遍,然后loop,只要前一点的终点大于后一点的起点,就返回False. It is just to tell if there is any overlap in intervals.
struct Solution {
bool canAttendMeetings(vector<Interval>& intervals) {
sort(intervals.begin(),intervals.end(),
[](const Interval &a,const Interval &b){ return a.start<b.start; });
for(int i=0;i<(int)intervals.size()-1;++i)
if(intervals[i].end>intervals[i+1].start)
return false;
return true;
}
};
- Java
class Solution {
public boolean canAttendMeetings(Interval[] intervals) {
if (intervals == null)
return false;
// Sort the intervals by start time
Arrays.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
Interval prev = null;
for (int i = 0; i < intervals.length; i++){
if(i==0){
prev = intervals[i];
} else {
Interval current = intervals[i];
if(prev.end > current.start){
return false;
}
prev = current;
}
}
return true;
}
}
45.5 253. Meeting Rooms II
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],…] (si < ei), find the minimum number of conference rooms required.
For example, Given [[0, 30],[5, 10],[15, 20]], return 2.
https://leetcode.com/problems/meeting-rooms-ii/
- CPP
struct Solution { // T:O(N)
int minMeetingRooms(vector<Interval>& ivs) {
vector<pair<int, bool>> vpr;
for(Interval& e: ivs)
vpr.emplace_back(e.start, true), vpr.emplace_back(e.end, false);
// when pr.first equals, for pr.second, false first!
sort(vpr.begin(), vpr.end());
int c=0, r=0;
for(auto& e: vpr){
if (e.second) ++c; else --c;
r=max(r,c);
}
return r;
}
};
- Java
http://www.cnblogs.com/yrbbest/p/5012534.html
class Solution { // T: O(NLogN)
public int minMeetingRooms(Interval[] intervals) {
if (intervals == null || intervals.length == 0)
return 0;
// Sort the intervals by start time
Arrays.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.start - b.start; }
});
// Use a min heap to track the minimum end time of merged intervals
PriorityQueue<Interval> heap = new PriorityQueue<Interval>(
intervals.length,
new Comparator<Interval>(){
public int compare(Interval a, Interval b) {
return a.end - b.end;
}
}
);
// start with the first meeting, put it to a meeting room
heap.offer(intervals[0]);
for (int i = 1; i < intervals.length; i++) {
// get the meeting room that finishes earliest
Interval interval = heap.poll();
if (intervals[i].start >= interval.end) {
// if the current meeting starts right after
// there's no need for a new room, merge the interval
interval.end = intervals[i].end;
} else {
// otherwise, this meeting needs a new room
heap.offer(intervals[i]);
}
// don't forget to put the meeting room back
heap.offer(interval);
}
return heap.size();
}
}
45.6 Gas Station
https://www.hackerrank.com/contests/algomars-11102016/challenges/gas-station-1
We are going to build a gas station alongside a road and we want to calculate the best place for it. There are a number of houses on either side of the road (with different distances) and we want the gas station to be in a fair distance from all of the houses. Write an efficient algorithm to find the best place for the gas station, assuming that the total distance that we are going to minimize is defined as the sum of all Euclidean distances from the houses to the gas station.
- Input Format
For the sake of brevity, assume the line equation representing the road is y = 0. Each house is then represented as a point in the 2-D plane with a Cartesian coordinate system wherein the road represents the x-asis. The first line of the input specifies the number of houses N. The next N lines specify the coordinates of the houses as one space separated pair of x and y per line.
- Constraints
None
- Output Format
The x-coordinate of the gas station, rounded to 2 digits after decimal point.
45.7 Largest Subarray
https://www.hackerrank.com/contests/algomars-10272016/challenges/largest-sub-array-with-given-sum
45.8 621. Task Scheduler
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order! Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ['A','A','A','B','B','B'], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
https://leetcode.com/problems/task-scheduler
https://leetcode.com/articles/task-scheduler
45.8.1 Algo 1: idle time slots
下面的是最优解:
struct Solution {
int leastInterval(vector<char>& tasks, int n) {
int c[26]={}; //counter
for(char e: tasks) c[e-'A']++;
sort(c, c+26); // O(1)
int mx=c[25]-1, idle=mx*n;
for(int i=24; i>=0 && c[i]>0; i--)
if((idle -= min(c[i], mx))<0)
return tasks.size();
return idle+tasks.size();
}
};
idle区域在string下面看起来是这样的:
AxxxxxAxxxxxAxxxxxAxxxxxAxxxxxxxxxxx...
|----------idle--------|
具体算法参考: http://bit.ly/2iOkgau
45.8.2 Algo 2: Priority Queue
这个题的逻辑还有点绕,写完之后用 Input: tasks = [‘A’,‘A’,‘A’,‘B’,‘B’,‘B’], n = 2; Output: 8 这个验证一下就知道了.
struct Solution {
int leastInterval(vector<char>& tasks, int n) {
int c[26]={}; // freq counter
for(char e: tasks) c[e-'A']++;
priority_queue<int> q;
for(int i=0;i<26;++i)
if(c[i]) q.push(c[i]);
int r=0;
while(!q.empty()){
vector<int> buf;
int i=n+1;
while(i--){ // do it n+1 times
if(!q.empty()){
if(q.top()-1>0) buf.push_back(q.top()-1);
q.pop();
}else{ if(buf.empty()) break; }
r++;
}
for(int k: buf) q.push(k);
}
return r;
}
};
The good part of this algorithm is it can output the final string/task schedule. 用pair of freq and char,可以每次r递增的时候把char append到一个string后面.
45.8.3 Follow up: Map + double pointers
这其实是经典面试题目的一个followup. Be noted that 这里的task order是不允许变化的! Task Schedule面经. 大致意思是每种task都有冷却时间,比如task1执行后,要经过interval时间后才能再次执行,求总共所需时间.
http://www.1point3acres.com/bbs/thread-188881-1-1.html
2016(4-6月) 码农类 硕士 全职 Facebook - 猎头 - 技术电面 |Other在职跳槽
刚刚面完,欧洲小哥,发上来攒人品
# Example 1
# Tasks: 1, 1, 2, 1
# Recovery interva (cooldown): 2
# Output: 7 (order is 1 _ _ 1 2 _ 1)
# Example 2
# Tasks: 1, 2, 3, 1, 2, 3.
# Recovery interval (cooldown): 3
# Output: 7 (order is 1 2 3 _ 1 2 3)
# Example 3
# Tasks: 1, 2, 3 ,4, 5, 6, 2, 4, 6, 1, 2, 4
# Recovery interval (cooldown): 6
# Output: 18 (1 2 3 4 5 6 _ _ 2 _ 4 _ 6 1 _ 2 _ 4)
用一个map<string, int>
, key是task字符,value是这个字符最近一次在结果list中出现的坐标, 如果当前任务在map里存在且最近一次在结果list中出现的坐标离当前坐标的距离还在cooldown距离内,就输出“_”,直到距离大于cooldown才输出当前任务,并且更新这个字符最近一次在结果list中出现的坐标.时间复杂度O(N).
45.9 468. Validate IP Address
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots (“.”), e.g.,172.16.254.1;
Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid.
IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (“:”). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases).
However, we don’t replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address.
Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.
Note: You may assume there is no extra space or special characters in the input string.
Example 1:
Input: "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".
Example 2:
Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Explanation: This is a valid IPv6 address, return "IPv6".
Example 3:
Input: "256.256.256.256"
Output: "Neither"
Explanation: This is neither a IPv4 address nor a IPv6 address.
https://leetcode.com/problems/validate-ip-address
struct Solution {
string validIPAddress(string IP) {
if(IP.find('.')!=string::npos)
return is_ipv4(IP);
else if(IP.find(':')!=IP.npos)
return is_ipv6(IP);
else
return "Neither";
}
string is_ipv4(string IP){
int i=0, c=0;
while((i=IP.find('.'))!=string::npos || c==3){
string t=(c!=3)?IP.substr(0,i):IP;
if(t.empty() || t.size()>3 || (t.size()>1 && t[0]=='0')) return "Neither";
for(char c: t)
if(!isdigit(c)) return "Neither";
int d=stoi(t);
if((c==0 && d==0)||d>255) return "Neither";
IP=IP.substr(i+1);
c++;
}
if(c!=4) return "Neither";
return "IPv4";
}
string is_ipv6(string IP){
int i=0, c=0;
while((i=IP.find(':'))!=string::npos || c==7){
string t=(c!=7)?IP.substr(0,i):IP;
if(t.empty() || t.size()>4) return "Neither";
for(char c: t)
if(!isdigit(c) && !(c>='a'&&c<='f') && !(c>='A'&&c<='F'))
return "Neither";
IP=IP.substr(i+1); // or IP.erase(0,i+1);
c++;
}
return "IPv6";
}
};
这道题主要考察split string.