LeetCode problem #217 Contains Duplicate @thatanjan @culesCoding

Solve LeetCode problem #217 Contains Duplicate

In this article we will be discussing the solution to the LeetCode problem #217 Contains Duplicate.

Problem Description:

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

1Example 1:
2
3Input: nums = [1,2,3,1]
4Output: true
5
6Example 2:
7
8Input: nums = [1,2,3,4]
9Output: false
10
11Example 3:
12
13Input: nums = [1,1,1,3,3,4,3,2,4,2]
14Output: true

Solution

You can also check the video solution.

To know if all the characters are the same we have to loop over the entire strings. We can use a hash map to store the count of each character in the string.

The algorithm is as follows:

  • Loop over the array
    • Check if the current number exists in the cache
      • If yes then return true
      • If not then add it to the cache

Code

1var containsDuplicate = function (nums) {
2 const cache = {}
3
4 for (const num of nums) {
5 if (num in cache) return true
6
7 cache[num] = 1
8 }
9
10 return false
11}

Complexity

Time Complexity: O(n) - We are looping over the entire array

Space Complexity: O(n) - We are storing the entire array in the cache

Shameless Plug

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostSolve LeetCode problem #121 Best Time to Buy and Sell Stock