The Set Object

var lengthOfLongestSubstring = function(s) {
const set = new Set();
//Create a set
let longest = 0;
let i = 0;
let j = 0;
// The goal is to use pointers i and j to find the longest range of [i, j]. When s[i, j] has a duplicate letter, we remove s[i] from the set and move i to the next position so we don't include s[prev i] in the next range calculation.

while (i < s.length && j < s.length) {
if (!set.has(s[j])) {
//if set does not include the value of s at index j
set.add(s[j]);
// add the value of s at index j to the set
longest = Math.max(longest, j - i + 1);
j += 1;
} else {
set.delete(s[i]);
i += 1;
}
}
return longest;
};

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How we handle inline styles with TypeScript and React

Send email using Amazon SES (NodeJS)

Bubble Sort — JS

Limitless Servers in a Serverless World

Setting up NodeJS on Ubuntu (Debian)

Bottom sheets in Flutter

Object.keys()

OnTriggerEnter or OnCollisionEnter?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
SunJet Liu

SunJet Liu

More from Medium

introduction

Kruskal’s Algorithm

Tasks we solve with Zabbix and Prometheus