Google – Plate and Dictionary


Google – Plate and Dictionary
给一个美国的车牌号(license plate),还有一个dictionary, 找出字典里包含车牌号中所有英文字母(车牌号里还有数字)的最短word。


http://chuansong.me/n/449596249789
车牌 RO 1287 ["rolling", "real", "WhaT", "rOad"] => "rOad"

follow up:
(1) 如果dictionary里有上百万个字,该如何加速
(2) 如果dictionary有上百万个字,然后給你上千个车牌号码,要你回传相对应的最短字串,该如何optimize?
若有N个字,车牌长度为M,求问N+M算法。


[Solution]
[Solution #1]
Brute Force很简单,拿plate和dictionary里的单词挨个比就好。
[Solution #2]
另一种方法是类似Google – Shortest Words Contain Input String,建inverted index.
建inverted index的时间为O(LEN), where LEN is sum of length of all words in the dictionary.
query time为O(len + LEN), where len is the length of plate. Worst case的情况出现于dictionary里面所有单词都包含车牌里的英语字母。
[Solution #3]
还有一种方法很巧妙。
  1. 把26个字母分别map到一个 prime number.
  2. 把每个单词对应的字母的质数乘起来,得到一个product,然后对dictionary建String -> product的map.
  3. Query的时候用同样方法计算plate的product,扫一遍dict, 谁能除得进plate的product,就说明包含Plate中的英文字母。
这样query的时间复杂度就为O(len + N)。 不过要注意乘积的overflow。
  public String plateAndDict(String[] dict, String plate) {
    Map<Character, Integer> primeMap = new HashMap<>();
    initMap(primeMap);
    plate = plate.toLowerCase();
    long platePrime = 1l;
    for (char c : plate.toCharArray()) {
      if (primeMap.containsKey(c)) {
        platePrime *= primeMap.get(c);
      }
    }
    String result = null;
    for (String word : dict) {
      String lowerWord = word.toLowerCase();
      long wordPrime = 1l;
      for (char c : lowerWord.toCharArray()) {
        if (primeMap.containsKey(c)) {
          wordPrime *= primeMap.get(c);
        }
      }
      if (wordPrime % platePrime == 0 && (result == null || word.length() < result.length())) {
        result = word;
      }
    }
    return result;
  }
  private void initMap(Map<Character, Integer> primeMap) {
    primeMap.put('a', 2);
    int prev = 2;
    for (char i = 'b'; i <= 'z'; i++) {
      int curr = nextPrime(prev);
      primeMap.put(i, curr);
      prev = curr;
    }
  }
  private int nextPrime(int n) {
    int result = n + 1;
    while (result % 2 == 0 || !isPrime(result)) {
      result++;
    }
    return result;
  }
  private boolean isPrime(int n) {
    for (int i = 2; i * i <= n; i++) {
      if (n % i == 0) {
        return false;
      }
    }
    return true;
  }


请问老师,原贴的讨论里面有提到将每个字母map到一个质数,一个单词就是所有字母表示质数的乘积。字典里的单词如果能被输入的字段除尽就是含有该输入字串的单词,然后求最短就好了。但是感觉这样还是需要每一个单词都要扫一遍字典,复杂度并没有降低。

有的同学认为,这道题可以用 trie 解决,但其实用 trie 并不能解决。

因为这个题说的是包含单词里的所有字母就好了,并没有要求顺序。也就是说从例子中来看,“orad” 也是包含 "RO" 的。

首先这类问题,给一个dictionary的,都是需要对 dictionary 做一些预处理的,因为dictionary又不会随时变化。既然是google的题,那么这个题多半就跟倒排索引有关系。一个直观的解决办法就是建立倒排索引。

比如 "Access" 这个单词,出现了 a, c, e, s 四个字母。所以把Access 分别放入 a, c, e, s 的队列中。

然后假如你来了一个车牌,包含字母'ace',如何找到 Access呢?方法是,把 a 的倒排拿出来,c的拿出来,e的拿出来。然后做一次归并。把同时出现在这三个字母里的倒排里的单词找到。为了加速算法,倒排在建立的时候,就可以先按照长度排序,然后相同长度的按照字母序排序。这样在归并的时候找到的第一个在三个字母的倒排队列中出现的单词,就是答案。

你可能会意识到,这种方法在某些情况下还是很慢,因为比如上百万个单词,一共只有26个不同的字母,那么平均下来,每个字母也有 1m/26 个单词包含它。归并的时候效率并不高。那么怎么解决呢?上面的算法的key只有一个字母,自然这个1m/26的分母比较小。我们要想办法把这个分母变大。答案是,可以用2个字母作为key。

以 Access 为例,出现的字母有 aces,那么把 ac, ae, as, ce, cs, es 作为倒排的key,把Access 放到这6个key的倒排列表中。当我们需要查询 ace 被哪些单词包含的时候,我们就可以归并 ac 和 e 的倒排表。这就比 并 a, c, e 的三个倒排表要快了。

再进一步,你可以用3个字母作为 key, access => {ace, acs, ces, aes},这样一口气就能找到 ace 了,无需归并。

进一步分析,你会发现这是一个 tradeoff,就是并不是用越多的字母作为key就越好。假如单词的平均长度是 L,那么C(L,1)是有多少个1元的key,C(L,2)是有多少个2元的key(基本是L^2的级别 ),C(L,3)是有多少个3元的key。。。





所以字母越多,一个单词被重复扔到各个倒排列表中的机会就越多。需要的存储空间也就越大。介于车牌的字母不是很多,我觉得差不多到3元的key就差不多可以了。

http://skyzjkang.blogspot.com/2015/04/license-plate-dictionary.html
原帖:http://www.meetqun.com/thread-2802-1-1.html
            http://www.meetqun.com/forum.php?mod=viewthread&tid=4901&ctid=41

题目:
“AC1234R” => CAR, ARC | CART, CARED not the shortest
OR4567S” => SORT, SORE | SORTED valid, not the shortest | OR is not valid, missing S

Google电面题目: 04/13/2015


1 <= letters <= 7
O(100) license plate lookups
O(4M) words in the dictionary


d1 = abc   000....111
d2 = bcd   000…..110
s1 = ac1234r  00001...101
s1 & d1 == s1 d1
s1 & d2 != s1

代码:
 int convert2Num(string s) {   
     int res = 0;   
     for (int i = 0; i < s.size(); ++i) {   
         if (!isdigit(s[i]) {   
             res |= 1 << (s[i] - ‘a’);    
         }   
     }   
     return res;   
 }   
   
 string find_shortest_word(string license, vector<string> words) {   
     int lis_num = convert2Num(license);   
     string res;    
     for (int i = 0; i < words.size(); ++i) {   
         int word_num = convert2Num(words[i]); // conversion;    
         if (lis_num & word_num == lis_num) {   
             if (res.empty() || res.size() > words[i].size())   
                 res = words[i]; // brute force; 可以sorting来减少比较次数   
         }   
     }   
     return res;   
 }  
<key, conversion number》
<words, save shortest length of words>
abc, abccc,   <000...111, abc>   

Follow up:
dictionary = { “BAZ”, “FIZZ”, “BUZZ” } | BAZ only has one Z


vector<int> map(26, 0);
a -> 0,   z -> 25;
map[s-’a’]++;
need[26];
need[i] < map[i]

代码:
 bool compare(const string& s1, const string& s2) {   
     return s1.size() < s2.size();   
 }    
   
 string find_shortest_string(string license, vector<string> words) {   
     sort(word.begin(), word.end(), compare);   
     int lic_num = convert2Num(license);   
     vector<int> map(26, 0);   
     for (auto i : license) {   
         if (!isdigit(i)) map[i-’a’]++;   
     }   
   
     for (int i = 0; i < words.size(); ++i) {   
         int word_num = convert2Num(words[i]);   
         // First check that it has all the letters, then check the counts   
         if (lic_num & word_num != lic_num) continue;   
   
         vector<int> word_map(26, 0);   
         for (auto k : words[i]) {   
             if (!isdigit(k)) map[k-’a’]++;   
         }    
         int j = 0;   
         for (; j < 26; ++j) {   
             if (word_map[‘a’+j] < map[‘a’+j]) break;   
         }   
         if (j == 26) return words[i];   
     }   
 }    

Follow up:
find_shortest_word(“12345ZZ”, dictionary) 50% => “FIZZ” | 50% => “BUZZ”
vector<string> s = {};
s[rand() % 2];


reservoir sampling;
FIZZ: s = words;
count = 1;
BUZZ: count++; count = 2;
rand() % count == 0 : s = BUZZ;
Read full article from Google – Plate and Dictionary

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