Created
April 19, 2022 21:19
-
-
Save anushshukla/26626ba12068b5ec4a5af630ea7dda06 to your computer and use it in GitHub Desktop.
Index of anagram sub string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| interface String { | |
| aio(substr: string): number; | |
| } | |
| // S -> Space complexity | |
| // T -> Time complexity | |
| // n -> length of the string | |
| // m -> length of the substr | |
| // Overall complexity -> T(n+m) & S(n) | |
| String.prototype.aio = function(substr: string): number { | |
| console.log('this:', this); | |
| console.log('substr:', substr); | |
| if (this.length === 0) { | |
| console.log('string is empty'); | |
| return -1; | |
| } | |
| const substrLen = substr.length; | |
| if (substrLen === 0) { | |
| console.log('substring is empty'); | |
| return -1; | |
| } | |
| // S(n) | |
| const letterPosMap = {} as Record<string, number>; | |
| // T(n) | |
| [...this].forEach((str, index) => { | |
| letterPosMap[str] = index; | |
| }) | |
| console.debug('letterPosMap:', letterPosMap); | |
| if (substrLen === 1) { | |
| return letterPosMap[substr] || -1 | |
| } | |
| let letterPositionsSum = 0; | |
| let letterPositionLowest = -1; | |
| // T(m) | |
| [...substr].every((substrLetter: string, index): boolean => { | |
| const letterFoundIndex = letterPosMap[substrLetter]; | |
| console.debug('letterFoundIndex:', letterFoundIndex); | |
| if (typeof letterFoundIndex === undefined) { | |
| console.log('substrLetter not found:', substrLetter) | |
| return false; // break loop | |
| } | |
| if (index === 0 || letterFoundIndex < letterPositionLowest) { | |
| letterPositionLowest = letterFoundIndex; | |
| } | |
| letterPositionsSum += letterFoundIndex; | |
| return true; | |
| }); | |
| console.debug('letterPositionLowest:', letterPositionLowest); | |
| return letterPositionLowest * substrLen + substrLen === letterPositionsSum | |
| ? letterPositionLowest | |
| : -1; | |
| } | |
| const isDebugMode = false; | |
| if (!isDebugMode) { | |
| console.debug = () => {}; | |
| } | |
| console.log('actor'.aio('cat')) // 0 | |
| console.log('actor'.aio('tar')) // -1 | |
| console.log('actor'.aio('rot')) // 2 | |
| console.log('actor'.aio('rto')) // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment