LeetCode: Permutation in String Solution

Notice the constraints

Approach

Notice that there's a constraint "s1 and s2 consist of lowercase English letters"

Maintain a sliding window with size of

s1.length

Use a counter base on character occurences to detect for permutation

Question now turns to "check if two strings are permutation of each other"

Implementation

1var checkInclusion = function (s1, s2) {
2 let [n1, n2] = [s1.length, s2.length]
3 let occurences = Array(26).fill(0)
4
5 const mutate = (charCode, dir) =>
6 (occurences[charCode - "a".charCodeAt(0)] += dir)
7
8 const isMatch = () => occurences.every(x => x === 0)
9
10 for (let i = 0; i < n1; i++) {
11 mutate(s1.charCodeAt(i), +1)
12 }
13
14 for (let i = 0; i < n2; i++) {
15 mutate(s2.charCodeAt(i), -1)
16 if (i - n1 >= 0) mutate(s2.charCodeAt(i - n1), +1)
17
18 if (isMatch()) return true
19 }
20
21 return false
22}

Comments

Loading comments...

Tags

leetcode

string

hash table

sliding window

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Longest Substring Without Repeating Characters

Sep 18, 2021

Sliding window uses two pointers?

Previous Post

LeetCode: Middle of the Linked List

Sep 16, 2021

Several ways

HoningJS

Search Posts