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:23Input: nums = [1,2,3,1]4Output: true56Example 2:78Input: nums = [1,2,3,4]9Output: false1011Example 3:1213Input: 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
- Check if the current number exists in the cache
Code
1var containsDuplicate = function (nums) {2 const cache = {}34 for (const num of nums) {5 if (num in cache) return true67 cache[num] = 18 }910 return false11}
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
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram : @thatanjan
- Twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: