Permutation in String
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Decide whether s2 contains some rearrangement (permutation) of s1 as a contiguous piece.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1How long must the matching piece of s2 be?
- Hint 2When the window moves one step, only two letters change their counts.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
You hold a Scrabble rack of two tiles, a and b. A long strip of tiles lies on the table. Slide a 2-tile-wide frame along the strip and each time ask: does the frame hold exactly the same tiles as my rack, in any order? When the frame moves one step, one tile leaves and one tile enters, so you update your tally instead of recounting.
- The obvious way
Sort every window of s2 and compare with sorted s1: O(n x m log m).
- The key insight
Count the letters of s1 (the rack). Slide a window of the same length along s2, adding the entering letter and removing the leaving one. Whenever the window's tally equals the rack's tally the window is a permutation. Comparing two 26-slot tallies is quick, so the whole scan is linear.
- The algorithm
- Short text longer than the long one? Answer False.
- Tally the letters of s1.
- Slide a same-length window along s2: add the letter entering, remove the letter leaving.
- After each slide, window tally equals the s1 tally? Answer True.
Watch it run
Examples1 = "ab", s2 = "eidbaooo"
Rack = {a, b}. First frame "ei" holds {e, i}: not equal.
frame {e, i}Where people slip
- Remove the leaving letter before comparing, so the frame holds exactly the right number of letters.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def check_inclusion(s1, s2):
size = len(s1)
if size > len(s2):
return False
rack = [0] * 26
frame = [0] * 26
for letter in s1:
rack[ord(letter) - ord("a")] += 1
for position, letter in enumerate(s2):
frame[ord(letter) - ord("a")] += 1 # letter enters
if position >= size:
frame[ord(s2[position - size]) - ord("a")] -= 1 # letter leaves
if frame == rack:
return True
return FalseNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.