filmov
tv
Leetcode: 217. Contains Duplicate Javascript Solution

Показать описание
When encountering problem 217. Contains Duplicate on Leetcode I initially thought to solve it by creating a new array to store distinct values, then comparing them to the values in the array "nums."
The initial solution used a for loop to iterate over each value of "nums" and check if the new array already includes the value using the Javascript built-in function "includes()."
However, this solution had a complexity of O(n^2) and I was only beating 10% of all submissions on Leetcode. I then looked at the code again and decided to try and improve the complexity by using a Javascript Set instead of an array.
This led to a solution with O(1) complexity for looking up values and I was able to beat over 99% of all submissions on Leetcode.
Solution on Github:
Medium article explaining thought process:
The initial solution used a for loop to iterate over each value of "nums" and check if the new array already includes the value using the Javascript built-in function "includes()."
However, this solution had a complexity of O(n^2) and I was only beating 10% of all submissions on Leetcode. I then looked at the code again and decided to try and improve the complexity by using a Javascript Set instead of an array.
This led to a solution with O(1) complexity for looking up values and I was able to beat over 99% of all submissions on Leetcode.
Solution on Github:
Medium article explaining thought process: