Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Actually, no windows shrinking is required to solve the task. We jus go forwar...

Viacheslav Lushchinskiy

Nov 15, 2022

Actually, no windows shrinking is required to solve the task. We jus go forward and keep track if we found a pattern or not. Just rephrase the task like this: Find out if there is a substring in a string that contains the same characters as in the pattern regardless the order. The task now becomes much simpler :) Solution in JS:

const f = (_str, _pattern) => { let patternLength = _pattern.length; let numberOfMatches = 0;

//transform to an array to use the splice method let _patternArr = [..._pattern];

// Algorithm idea: all the char in the pattern regardless the order // should be found in a substring.

//Just reset the pattern if a foreign char is found for (let windowEnd = 0; windowEnd < _str.length; windowEnd++) { const rightChar = _str[windowEnd]; const index = _patternArr.indexOf(rightChar);

// if we found a match, remove it from the pattern if (index >= 0) { numberOfMatches += 1; _patternArr.splice(index, 1); } else { // if we found a foreign char, reset the pattern to initial state numberOfMatches = 0; _patternArr = [..._pattern]; } if (numberOfMatches === patternLength) return true; } return false; };

1

0

Comments
Comments

On this page