LeetCode 1016 - Binary String With Substrings Representing 1 To N


https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/
Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.

Example 1:
Input: S = "0110", N = 3
Output: true
Example 2:
Input: S = "0110", N = 4
Output: false

Note:
  1. 1 <= S.length <= 1000
  2. 1 <= N <= 10^9
X.
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/260882/C%2B%2B-O(S-log-N)-vs.-O(N-*-(S-%2B-log-N))
We can process the entire string and track all numbers [1..N] that we can build.
OR
We can generate binary string representation for [1..N], and search for it in the string.

Solution 1

  • For each non-zero position i in S, gradually build num while num <= N.
  • Track each num in seen, increment X for new num.
  • Return true if we built all numbers from 1 to N (X == N).
bool queryString(string S, int N, int X = 0) {
  vector<bool> seen(N);
  for (auto i = 0; i < S.size() && X < N; ++i) {
    if (S[i] == '0') continue;
    for (auto j = i, num = 0; num <= N && j < S.size(); ++j) {
      num = (num << 1) + S[j] - '0';
      if (num > 0 && num <= N && !seen[num - 1]) {
        ++X;
        seen[num - 1] = true;
      }
    }
  }
  return X == N;
}

Complexity Analysis

Runtime: O(S log N), where S is the string size. For every position, we analyze log N digits.
Memory: O(N) as we need to track all numbers from 1 to N.

http://www.noteanddata.com/leetcode-1023-Binary-String-With-Substrings-Representing-1-To-N-google-interview-problem-java-solution-note.html
  1. 感觉直接遍历N肯定不可行(没想到其实是可以的,因为跳出循环很快, 然后看S, S总共就只有1000位, 那么S的子字符串最多也就10001000, 而实际上, 因为整数最多只有32位二进制, 那么对于每一个index=i, 直接看len=[1,32], 那么, S的子字符串最多也就100032种可能, 所以如果N > s.length() * 32, 就可以直接return false
  2. 然后对每一个index求所有可能的子字符串, 然后放到一个set里面, 然后最后判断这个set是否包含了[1,N]的所有数就好
java题解代码
  1. 这里我第一次知道原来32位的二进制的0和1, 不能被全部解析到整数, 比如"10010010011001011010101100110110", 这我就有点晕了, 为什么会出现这样的情况呢?
  2. Integer.parseInt(s, base), 字符串不需要补齐到32位
  3. 后来看了下其他人很多是采用直接数字操作转化到十进制的, 这个后面再学习一下
时间复杂度
O(32*M), 其中M是S的长度

public boolean queryString(String S, int N) {
    if(N > S.length() * 32) return false;
    Set<Integer> set = new HashSet<>();
    for(int i = 0; i < S.length(); ++i) {
        for(int len = 1; len <= 32; ++len) {
            if(i+len <= S.length()) {
                String sub = S.substring(i, i+len);    
                try {
                    int value = Integer.parseInt(sub, 2);
                    set.add(value);
                }
                catch(Exception e) {
                }
            }
        }
    }
    for(int i = 1; i <= N; ++i) {
        if(!set.contains(i)) {
            return false;
        }
    }
    return true;
}

X.  Brute Force
比较惊讶的是输入数据N是比较大大,可是brute force也可以过。。。可能主要是跳出循环比较快
1. 后来看了下, 直接brute force循环N从大到小也可以过
没想到, 从小到大循环也可以过
Actuall looking at most of the solution wich are iterating over N one might feel as if it should give TLE
But the trick here is the fast eleminations
"You cannot fit too many numbers into 1000-character binary string..." (refer to @votrubac 's solution most rated one for better approaches)
We return false as soon as we dont find a perticular no. hence the probability of returning false is very high before the time limit exceeds
Hence it alomost never exceeds limit
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/260847/JavaC%2B%2BPython-O(S2)
The construction of S is a NP problem,
it's time consuming to construct a short S.
I notice S.length <= 1000, which is too small to make a big N.
This intuition lead me to the following 1-line python solution,
which can be implemented very fast.
##Explanation:
Check if S contains binary format of N,
If so, continue to check N - 1.

Time Complexity

  1. Prove I, check number of substring
Pick two indices, there are at most S^2 substrings,
so S can contains at most S^2 integers
Time complexity upper bound O(S^2)
  1. Prove II, Check the continuous digits
    Meanwhile I know the interviewer and my reader won't be satisfied,
    as they want no more "cheat".
Here I have a brief demonstration to give the time complexity an acceptable upper bound.
Have a look at the number 1001 ~ 2000 and their values in binary.
1001 0b1111101001
1002 0b1111101010
1003 0b1111101011
...
1997 0b11111001101
1998 0b11111001110
1999 0b11111001111
2000 0b11111010000
The number 1001 ~ 2000 have 1000 different continuous 10 digits.
The string of length S has at most S - 9 different continuous 10 digits.
So S <= 1000N <= 2000.
So S * 2 is a upper bound for N.
If N > S * 2, we can return false directly.
It's the same to prove with the numbers 512 ~ 1511, or even smaller range.
Time complexity upper bound O(S)
    public boolean queryString(String S, int N) {
        for (int i = N; i > N / 2; --i)
            if (!S.contains(Integer.toBinaryString(i)))
                return false;
        return true;
    }

X. https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/260907/easy-Java-solution
    public boolean queryString(String S, int N) {
        for(int i =1; i<=N; i++){
            String b = Integer.toBinaryString(i);
            if(!S.contains(b))return false;
        }
        return true;
    }
Small Improvisation: If we observe the binary patterns, we only need to search for the 2nd power of two value, starting from N. Ex: if N=19, we need to search 19 to 8, remaining will be always be there.


https://www.acwing.com/solution/LeetCode/content/1251/
给定一个二进制字符串 S(一个仅由若干 ‘0’ 和 ‘1’ 构成的字符串)和一个正整数 N,如果对于从 1 到 N 的每个整数 X,其二进制表示都是 S 的子串,就返回 true,否则返回 false。

样例

输入:S = "0110", N = 3
输出:true
输入:S = "0110", N = 4
输出:false

(子串枚举) O(S.length)
  • 直接枚举 S 的长度不超过 30 的子串,如果子串构成了 1 到 N 中的数字,则加到一个集合中,最后判断集合的大小是否等于 N

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