Simple JavaScript Solution O(n) time


  • 2
    var findAnagrams = function(s, p) {
      let pMap = {};
      for(let i = 0; i < p.length; ++i) {
        if (pMap[p[i]]) {
          pMap[p[i]]++;
        } else {
          pMap[p[i]] = 1;
        }
      }
      let result = [];
      let count = p.length;
      for (let i = 0; i < p.length; ++i) {
        if (pMap[s[i]] !== undefined && pMap[s[i]]-- > 0) {
          --count;
        }
      }
      for(let i = 0; i < s.length - p.length + 1; ++i) {
        if (count === 0) {
          result.push(i);
        }
        if (pMap[s[i]] !== undefined && pMap[s[i]]++ >= 0 ) {
          ++count;
        }
        if (pMap[s[i+p.length]] !== undefined && pMap[s[i+p.length]]-- > 0) {
          --count;
        }
      }
      return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.