The Set Object
While practicing my algorithms and data structures, I came across a standard built in object for Javascript. The “Set” object. This handy guy lets you store unique values of any type in a collection of values! Its super handy when you are doing algorithms that want you to determine non-repeating or unique strings, etc.
I would start of by doing something like the following: const set = new Set();
Set has 4 Instance methods.
Set.add(value) : Appends value
to the Set
object. Returns the Set
object with added value.
Set.has(value) : Returns a boolean asserting whether an element is present with the given value in the Set
object or not.
Set.delete(value) : Removes the element associated to the value
and returns a boolean asserting whether an element was successfully removed or not. Set.prototype.has(value)
will return false
afterwards.
Set.clear() : Removes all elements from the Set
object.
Set has 1 instance property.
Set.size : Returns the number of values in the Set
object.
With this basic knowledge you can solve leetcodes medium difficulty problem ?Longest Substring Without Repeating Characters”.
The question is as follows: Given a string s
, find the length of the longest substring without repeating characters.
I solved it with the following code
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;
};
Please check out MDN Source for a lot of examples and further information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set