|
| 1 | +/* |
| 2 | +Smallest distinct window |
| 3 | +======================== |
| 4 | +
|
| 5 | +Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. |
| 6 | +For eg. A = “aabcbcdbca”, then the result would be 4 as of the smallest window will be “dbca”. |
| 7 | +
|
| 8 | +Example 1: |
| 9 | +Input : "AABBBCBBAC" |
| 10 | +Output : 3 |
| 11 | +Explanation : Sub-string -> "BAC" |
| 12 | +
|
| 13 | +Example 2: |
| 14 | +Input : "aaab" |
| 15 | +Output : 2 |
| 16 | +Explanation : Sub-string -> "ab" |
| 17 | +
|
| 18 | +Example 3: |
| 19 | +Input : "GEEKSGEEKSFOR" |
| 20 | +Output : 8 |
| 21 | +Explanation : Sub-string -> "GEEKSFOR" |
| 22 | +
|
| 23 | +Your Task: |
| 24 | +You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as inputs and returns the length of the smallest such string. |
| 25 | +
|
| 26 | +Expected Time Complexity: O(256.N) |
| 27 | +Expected Auxiliary Space: O(256) |
| 28 | +
|
| 29 | +Constraints: |
| 30 | +1 ≤ |S| ≤ 105 |
| 31 | +String may contain both type of English Alphabets. |
| 32 | +*/ |
| 33 | + |
| 34 | +string findSubString(string str) |
| 35 | +{ |
| 36 | + int n = str.size(); |
| 37 | + int dist_count = 0; |
| 38 | + bool visited[256] = {false}; |
| 39 | + |
| 40 | + for (int i = 0; i < n; i++) |
| 41 | + { |
| 42 | + if (visited[str[i]] == false) |
| 43 | + { |
| 44 | + visited[str[i]] = true; |
| 45 | + dist_count++; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + int start = 0, start_index = -1, min_len = INT_MAX; |
| 50 | + |
| 51 | + int count = 0; |
| 52 | + int curr_count[256] = {0}; |
| 53 | + |
| 54 | + for (int i = 0; i < n; ++i) |
| 55 | + { |
| 56 | + curr_count[str[i]]++; |
| 57 | + if (curr_count[str[i]] == 1) |
| 58 | + count++; |
| 59 | + if (count == dist_count) |
| 60 | + { |
| 61 | + while (curr_count[str[start]] > 1) |
| 62 | + { |
| 63 | + if (curr_count[str[start]] > 1) |
| 64 | + curr_count[str[start]]--; |
| 65 | + start++; |
| 66 | + } |
| 67 | + |
| 68 | + int len_window = i - start + 1; |
| 69 | + if (min_len > len_window) |
| 70 | + { |
| 71 | + min_len = len_window; |
| 72 | + start_index = start; |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return str.substr(start_index, min_len); |
| 78 | +} |
0 commit comments