Leetcode: Google interview questions #4


Leetcode: Google interview questions #4
REF http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=136847&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26sortid%3D311
给我小哥没有废话直接上题
我coding速度太慢,只面了一道题目
.鐣欏璁哄潧-涓€浜�-涓夊垎鍦�
给出一个迭代器,迭代器里存了很多个类R的实例, 类R里只有两个参数,都是String类型,分别代表Parent 和 Child,child只有一个Parent,Parent 可以有任意数量child
按所给示例输出所有的层级关系
eg:
A
  B1
  B2
    C1
    C2
  B3
    D1. 1point3acres.com/bbs
    D2. 1point3acres.com/bbs


就是建立一个compiler里面的inheritance graph,然后打印 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
struct TreeNode{
    string parent;
    string name;
    vector<TreeNode *> children;
    TreeNode(string p, string n) {
        parent = p;
        name = n;
    }
};
 
class A{
public:
    string parent;
    string child;
};
 
 
void printRecursively(TreeNode *root, string tab) {
    if (root == NULL) return;
    cout << tab << root->name << endl;
    for (int i = 0; i < root->children.size(); i++) {
        printRecursively(root->children[i],tab + "    ");
    }
}
 
void printGraph(vector<A> &source) {
    unordered_map<string,TreeNode*> dic;
     
    for (int i = 0; i < source.size(); i++) {
      
        TreeNode *p = NULL, *c = NULL;
        if (dic.find(source[i].parent) == dic.end()) {
            p = new TreeNode("",source[i].parent); 
            dic[source[i].parent] = p;
        }
        if (dic.find(source[i].child) == dic.end()) {
            c = new TreeNode(source[i].parent,source[i].child);
            dic[source[i].child] = c;
        }
        p = dic[source[i].parent];
        c = dic[source[i].child];
        p->children.push_back(c);
    }
     
    for (auto t : dic) {
        if (dic[t.first]->parent.length() == 0) {
            printRecursively(dic[t.first],"");
        }
    }
}
 
int main()
{
    A a1;
    a1.parent = "A";
    a1.child = "B1";
    A a2;
    a2.parent = "A";
    a2.child = "B2";
    A a3;
    a3.parent = "A";
    a3.child = "B3";
     
    A b1;
    b1.parent = "B2";
    b1.child = "C1";
    A b2;
    b2.parent = "B2";
    b2.child = "C2";
     
    A c1;
    c1.parent = "B3";
    c1.child = "D1";
    A c2;
    c2.parent = "B3";
    c2.child = "D2";
     
    vector<A> v;
    v.push_back(a1);
    v.push_back(a2);
    v.push_back(a3);
    v.push_back(b1);
    v.push_back(b2);
    v.push_back(c1);
    v.push_back(c2);
     
    printGraph(v);
}
---------------------------------------------------------------------------
REF http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=134335&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26sortid%3D311
4月底MTV面的onsite, 很奇怪是5面,至今没消息,直接上面经
鏉ユ簮涓€浜�.涓夊垎鍦拌鍧�. 
1.日本大叔-google 1point3acres
来晚了20分钟导致后面很紧。先写反转链表,然后第二题把链表变成a1->an->a2->an-1
LC reorder list
2.白人小哥+沉默的阿三
第一题是path sum难度一样的dp水果。 第二题给画布上的几个线段,问怎么画最快(移动画笔会浪费时间). Waral 鍗氬鏈夋洿澶氭枃绔�,
待写
3.阿三
到这面的时候才20分钟后面找我吃饭的大叔就来了,草草写完,给一个字符串,问可否组成一个新串使得每两个相邻字符不重复
重复,见Google interview questions #2 onsite第1题
. Waral 鍗氬鏈夋洿澶氭枃绔�,
午饭是个黑叔叔,用手直接抓食物吃,震精

4.光头小白
先问简历,然后又是一个path sum难度一样的dp水果
. 1point 3acres 璁哄潧
5.白人小帅
q: 玩过扫雷吗?
a: yes
q: 实现它
a: wtf??

---------------------------------------------------------------------------------------
REF http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=137928&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26sortid%3D311
可能是因为我做得慢,总共就做了一道题,就是一个游戏。 
input string:“+++--++-+”
游戏规则:每人每次可以 flip "++" to "--"(必须是相邻的)


第一问:generate all possible moves
第二问:determine if this player can will
Extra:这两个问题的implementation的Big-O

补充内容 (2015-7-12 13:13):
下个人没法flip了这个人就赢;all possible moves for next flip
permutation,  O(n!) 
T(n) = T(n - 1) + T(n - 1) + T(n - 1)...... + c = (n - 1) * T(n - 1) + c
T(n - 1) = (n - 2) * T(n - 2)
T(n - 2) = (n - 3) * T(n - 2)
.....
So T(n) = n!
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
bool canWin(string s) {
    int start = -1,end = -1;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '+') {
            if (start != -1 && i - start > 0) {
                string t = s;
                t[start] = '-';
                t[i] = '-';
                if (!canWin(t)) return true;
                start++;
            }else {
                start = i;
            }
        }else {
            start = -1;
        }
    }
  
    return false;
}

另一方法:博弈论,可达到O(n^2), 关键词game theory, nimber, grundy number
http://www.1point3acres.com/bbs/thread-137953-1-1.html
----------------------------------------------------------------------------------------
Linked List e.g 1->5->2->3->7
Modify it so that it becomes: 1->7->5->3->2
一头一尾,第二头第二尾,O(1)空间复杂度,O(n)时间复杂度
-----------------------------------------------------------------------------------

Given a bunch of N random points in space, how would you

   draw a line such that N/2 of them were to the left of the line and N/2 to the right of it. Complexity 

按x坐标用quick select,找出median,只需要O(n) 
-------------------------------------------------
Given an unbalanced binary tree, write code to select a node at random (each node has an equal probability of being selected).
reservoir sampling

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void helper(TreeNode *root, int &count, int choice) {
 if (root == NULL) return NULL;
 count++;
 if (rand(1,count) == 1) {
  choice = root;
 }
  
 helper(root->left,count,choice);
 helper(root->right,count,choice);
}
 
TreeNode *findRandomNode(TreeNode *root) {
 TreeNode *choice = NULL;
 int count = 0;
 return helper(root,count,choice);
}



------------------------------
给一个array和target,找出在array里与target最接近的值的index

类似LC search insert position

----------------------------------------------------
REF http://www.mitbbs.com/article_t/JobHunting/33010083.html
onsite
1. card shuffler:shuffle的程序是一个简单的array,array里的值代表当前位置卡
片的下一个位置 
e.g 当前卡片位置ABCDE shuffle array是01234的话下个卡片位置还是ABCDE,43210的
话下个卡片位置是EDCBA。
问给定一个shuffle array,不断用这个array去shuffle,能否得到最初的card deck,
能得话要多少次。 
吐槽下,面试官是个三哥,全程非常严肃/黑脸,我说句话就用小本子记下搞得我很紧
张。我说用java写可以吗,曰可以,刚写了两行问我add是啥意思,不知道是想考我基
础知识还是不懂java。

O(n), 对shuffle里面的每一个点都走一遍,最后走回起始点,走过的路径全部mark起来,记录count。mark过的可以直接跳过
最后取所以count的最小公约数即可 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int getSmallest(int i, int j) {
    for (int s = 1; s <= j; s++) {
        if (s * i % j == 0) return s * i;
    }
}
 
int jumpBack(vector<int> &shuffle) {
    vector<int> visit(shuffle.size(),-1);
    int count = 0, preCount = 1;
    for (int i = 0; i < shuffle.size(); i++) {
        count = 0;
        int index = i;
        while (visit[index] == -1) {
            count++;
            visit[index] = shuffle[i];
            index = shuffle[index];
            if (visit[index] != -1 && visit[index] != visit[i]) return -1;
        }
        if (count != 0) preCount = getSmallest(count,preCount);   
                
    }
     
    return preCount;
}
2. 给定一个binary search tree,返回range内所有key,key可以有重复。 
版上出现了多次的把一个数拆成任意个平方和的最小拆法。
DP,重复
面试官是中年国人大叔,除了告诉我题目是啥就在电脑上自顾自工作,问话要问两遍才
有反应。写完说我程序有问题,查了半天查不出bug,然后指出我漏了个尖括号,跪了
。。

3. 版上出现多次的longest consecutive sequence in tree 
follow up 如何加速,memory放不下怎么办。
国人小哥比较nice,但是只要我不和他主动说话绝不主动和我说话,因为前两场心情略
糟糕写完题目在白板前发呆,哥们就望着我啥也不说,尴尬。。当然也不怪他我自己比
较紧张,回家发现有很弱智的bug但小哥没提不知道怎么回事,可能放我水了

4. 设计个用bit形式表示时间(小时:分钟)的clock,
e.g 10:15可以写作1010:1111,每个bit是一个小灯泡,打印所有有且仅有n盏灯亮着的
时间,
e.g. n=0就只有0:0一种可能。

面试官是亚裔年轻mm,话不多人很cool,但是思路清晰会引导面试者,感觉碰到懂得引
导面试者或冷漠面试官对面试人表现会有很大影响,真的是看运气了。

5.算法游戏,给一个只有+-两种字符的array,两个玩家,轮到某个玩家他可以任选
两个连续的--将他们变成++,如果某个玩家发现自己无法行动则赢得游戏,要求写
isWin(String s)判断先行动的玩家能否赢。
followup 如何优化,时间上和空间上。
面试官是做android前端的白人mm,非常活泼健谈,一路聊天愉快,面完就感觉她会给
强推。
Read full article from Leetcode: Google interview questions #4

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts