Find all permutations of smaller string s in string b (JavaScript) -
i've been trying find o(n) solution following problem: find number of anagrams (permutations) of string s in string b, s.length smaller b.length
i read optimal solution involves keeping track of frequencies of characters in smaller string , doing same sliding window moves across larger string, i'm not sure how implementation works. right solution doesn't work (see comments) if did, take o(s + sn) time.
edit: sample input: ('aba', 'abaab')
. output: 3, because 'aba'
exists in b starting @ index 0, , 'baa'
@ 1, , 'aab'
@ 2.
function anagramsinstr(s,b) { //o(s) let freq = s.split("").reduce((map, el) => { map[el] = (map[el] + 1) || 1; return map; }, {}); let = 0, j = s.length; // o(n) (let char in b.split("")) { // o(s) if (b.length - char + 1 > s.length) { let window = b.slice(i,j); let windowfreq = window.split("").reduce((map, el) => { map[el] = (map[el] + 1) || 1; return map; }, {}); // somewhere here compare frequencies of chars found in window frequencies hash defined in outer scope. i++; j++; } } }
read through comments , let me know if have questions:
function countanagramoccurrences(s, b) { var matchcount = 0; var scounts = {}; // counts letters in s var bcounts = {}; // counts letters in b // construct scounts (var = 0; < s.length; i++) { scounts[s[i]] = (scounts[s[i]] || 0) + 1; } // letters occur in scounts var letters = object.keys(scounts); // each letter in b (var = 0; < b.length; i++) { // maintain sliding window // if have s.length items in counts, remove oldest 1 if (i >= s.length) { bcounts[b[i-s.length]] -= 1; } // increment count letter we're looking @ bcounts[b[i]] = (bcounts[b[i]] || 0) + 1; // test match (b counts == s counts) var match = true; (var j = 0; j < letters.length; j++) { if (scounts[letters[j]] !== bcounts[letters[j]]) { match = false; break; } } if (match) { matchcount += 1; } } return matchcount; } console.log(countanagramoccurrences('aba', 'abaab')); // 3
edit
a note runtime: sort of o(nk + m), n length of s, m length of b, , k number of unique characters in b. since m less n, can reduce o(nk), , since k bounded fixed constant (the size of alphabet), can further reduce o(n).
Comments
Post a Comment