LeetCode Meditations (79 Part Series)
1 LeetCode Meditations: Introduction
2 LeetCode Meditations — Chapter 1: Arrays & Hashing
… 75 more parts…
3 LeetCode Meditations: Contains Duplicate
4 LeetCode Meditations: Valid Anagram
5 LeetCode Meditations: Two Sum
6 LeetCode Meditations: Group Anagrams
7 LeetCode Meditations: Top K Frequent Elements
8 LeetCode Meditations: Product of Array Except Self
9 LeetCode Meditations: Longest Consecutive Sequence
10 LeetCode Meditations — Chapter 2: Two Pointers
11 LeetCode Meditations: Valid Palindrome
12 LeetCode Meditations: 3Sum
13 LeetCode Meditations: Container with Most Water
14 LeetCode Meditations — Chapter 3: Sliding Window
15 LeetCode Meditations: Best Time to Buy and Sell Stock
16 LeetCode Meditations: Longest Substring without Repeating Characters
17 LeetCode Meditations: Longest Repeating Character Replacement
18 LeetCode Meditations: Minimum Window Substring
19 LeetCode Meditations — Chapter 4: Stack
20 LeetCode Meditations: Valid Parentheses
21 LeetCode Meditations — Chapter 5: Binary Search
22 LeetCode Meditations: Find Minimum in Rotated Sorted Array
23 LeetCode Meditations: Search in Rotated Sorted Array
24 LeetCode Meditations — Chapter 6: Linked Lists
25 LeetCode Meditations: Reverse Linked List
26 LeetCode Meditations: Merge Two Sorted Lists
27 LeetCode Meditations — Interlude: Fast & Slow Pointers
28 LeetCode Meditations: Reorder List
29 LeetCode Meditations: Remove Nth Node From the End of List
30 LeetCode Meditations: Linked List Cycle
31 LeetCode Meditations: Merge K Sorted Lists
32 LeetCode Meditations — Chapter 7: Trees
33 LeetCode Meditations: Invert Binary Tree
34 LeetCode Meditations: Maximum Depth of Binary Tree
35 LeetCode Meditations: Same Tree
36 LeetCode Meditations: Subtree of Another Tree
37 LeetCode Meditations: Lowest Common Ancestor of a Binary Search Tree
38 LeetCode Meditations: Binary Tree Level Order Traversal
39 LeetCode Meditations: Validate Binary Search Tree
40 LeetCode Meditations: Kth Smallest Element in a BST
41 LeetCode Meditations: Construct Binary Tree from Preorder and Inorder Traversal
42 LeetCode Meditations: Binary Tree Maximum Path Sum
43 LeetCode Meditations: Serialize and Deserialize Binary Tree
44 LeetCode Meditations — Chapter 8: Heap/Priority Queue
45 LeetCode Meditations: Find Median from Data Stream
46 LeetCode Meditations — Chapter 9: Backtracking
47 LeetCode Meditations: Combination Sum
48 LeetCode Meditations: Word Search
49 LeetCode Meditations — Chapter 10: Tries
50 LeetCode Meditations: Implement Trie (Prefix Tree)
51 LeetCode Meditations: Design Add and Search Words Data Structure
52 LeetCode Meditations: Word Search II
53 LeetCode Meditations — Chapter 11: Graphs
54 LeetCode Meditations: Number of Islands
55 LeetCode Meditations: Clone Graph
56 LeetCode Meditations: Pacific Atlantic Water Flow
57 LeetCode Meditations: Course Schedule
58 LeetCode Meditations — Chapter 12: Dynamic Programming
59 LeetCode Meditations: Climbing Stairs
60 LeetCode Meditations: House Robber
61 LeetCode Meditations: House Robber II
62 LeetCode Meditations: Longest Palindromic Substring
63 LeetCode Meditations: Palindromic Substrings
64 LeetCode Meditations: Decode Ways
65 LeetCode Meditations: Coin Change
66 LeetCode Meditations: Maximum Product Subarray
67 LeetCode Meditations: Word Break
68 LeetCode Meditations: Longest Increasing Subsequence
69 LeetCode Meditations — Chapter 13: Intervals
70 LeetCode Meditations: Insert Interval
71 LeetCode Meditations: Merge Intervals
72 LeetCode Meditations: Non-overlapping Intervals
73 LeetCode Meditations — Chapter 14: Bit Manipulation
74 LeetCode Meditations: Number of 1 Bits
75 LeetCode Meditations: Counting Bits
76 LeetCode Meditations: Reverse Bits
77 LeetCode Meditations: Missing Number
78 LeetCode Meditations: Sum of Two Integers
79 LeetCode Meditations: Conclusion
For this problem, let’s start with the description:
Given an integer array
nums
, returntrue
if any value appears at least twice in the array, and returnfalse
if every element is distinct.
For example:
<span>[</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>,</span> <span>1</span><span>]</span> <span>// true</span><span>[</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>,</span> <span>4</span><span>]</span> <span>// false</span><span>[</span><span>1</span><span>,</span> <span>1</span><span>,</span> <span>1</span><span>,</span> <span>3</span><span>,</span> <span>3</span><span>,</span> <span>4</span><span>,</span> <span>3</span><span>,</span> <span>2</span><span>,</span> <span>4</span><span>,</span> <span>2</span><span>]</span> <span>// true</span><span>[</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>,</span> <span>1</span><span>]</span> <span>// true</span> <span>[</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>,</span> <span>4</span><span>]</span> <span>// false</span> <span>[</span><span>1</span><span>,</span> <span>1</span><span>,</span> <span>1</span><span>,</span> <span>3</span><span>,</span> <span>3</span><span>,</span> <span>4</span><span>,</span> <span>3</span><span>,</span> <span>2</span><span>,</span> <span>4</span><span>,</span> <span>2</span><span>]</span> <span>// true</span>[1, 2, 3, 1] // true [1, 2, 3, 4] // false [1, 1, 1, 3, 3, 4, 3, 2, 4, 2] // true
Enter fullscreen mode Exit fullscreen mode
We can use a Set
which only keeps the values without duplicates.
For each example, it would look like this:
<span>new</span> <span>Set</span><span>([</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>,</span> <span>1</span><span>]);</span><span>// -> Set(3) { 1, 2, 3 }</span><span>new</span> <span>Set</span><span>([</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>,</span> <span>4</span><span>]);</span><span>// -> Set(4) { 1, 2, 3, 4 }</span><span>new</span> <span>Set</span><span>([</span><span>1</span><span>,</span> <span>1</span><span>,</span> <span>1</span><span>,</span> <span>3</span><span>,</span> <span>3</span><span>,</span> <span>4</span><span>,</span> <span>3</span><span>,</span> <span>2</span><span>,</span> <span>4</span><span>,</span> <span>2</span><span>]);</span><span>// -> Set(4) { 1, 3, 4, 2 }</span><span>new</span> <span>Set</span><span>([</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>,</span> <span>1</span><span>]);</span> <span>// -> Set(3) { 1, 2, 3 }</span> <span>new</span> <span>Set</span><span>([</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>,</span> <span>4</span><span>]);</span> <span>// -> Set(4) { 1, 2, 3, 4 }</span> <span>new</span> <span>Set</span><span>([</span><span>1</span><span>,</span> <span>1</span><span>,</span> <span>1</span><span>,</span> <span>3</span><span>,</span> <span>3</span><span>,</span> <span>4</span><span>,</span> <span>3</span><span>,</span> <span>2</span><span>,</span> <span>4</span><span>,</span> <span>2</span><span>]);</span> <span>// -> Set(4) { 1, 3, 4, 2 }</span>new Set([1, 2, 3, 1]); // -> Set(3) { 1, 2, 3 } new Set([1, 2, 3, 4]); // -> Set(4) { 1, 2, 3, 4 } new Set([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]); // -> Set(4) { 1, 3, 4, 2 }
Enter fullscreen mode Exit fullscreen mode
In that case, the difference between the size of the set and the length of the original array will tell us whether it contains duplicates or not. If they are not equal to each other, that means the array has duplicates.
Using TypeScript, my solution was this:
<span>function</span> <span>containsDuplicate</span><span>(</span><span>nums</span><span>:</span> <span>number</span><span>[]):</span> <span>boolean</span> <span>{</span><span>return</span> <span>!</span><span>(</span><span>new</span> <span>Set</span><span>(</span><span>nums</span><span>).</span><span>size</span> <span>===</span> <span>nums</span><span>.</span><span>length</span><span>);</span><span>};</span><span>function</span> <span>containsDuplicate</span><span>(</span><span>nums</span><span>:</span> <span>number</span><span>[]):</span> <span>boolean</span> <span>{</span> <span>return</span> <span>!</span><span>(</span><span>new</span> <span>Set</span><span>(</span><span>nums</span><span>).</span><span>size</span> <span>===</span> <span>nums</span><span>.</span><span>length</span><span>);</span> <span>};</span>function containsDuplicate(nums: number[]): boolean { return !(new Set(nums).size === nums.length); };
Enter fullscreen mode Exit fullscreen mode
It’s obvious from the size and length comparison that this solution works, and indeed, it passes the tests.
Time & space complexity
My guess for the time complexity is that it’s O ( n ) O(n) O(n) , because the Set
constructor iterates over each element in the array it is given as the argument.
I think that the space complexity is also O ( n ) O(n) O(n) , because in the worst case where each element is unique, Set
needs to allocate memory for each of them.
Using Python
We can translate this solution into Python like this as well:
<span>class</span> <span>Solution</span><span>:</span><span>def</span> <span>containsDuplicate</span><span>(</span><span>self</span><span>,</span> <span>nums</span><span>:</span> <span>List</span><span>[</span><span>int</span><span>])</span> <span>-></span> <span>bool</span><span>:</span><span>return</span> <span>len</span><span>(</span><span>set</span><span>(</span><span>nums</span><span>))</span> <span>!=</span> <span>len</span><span>(</span><span>nums</span><span>)</span><span>class</span> <span>Solution</span><span>:</span> <span>def</span> <span>containsDuplicate</span><span>(</span><span>self</span><span>,</span> <span>nums</span><span>:</span> <span>List</span><span>[</span><span>int</span><span>])</span> <span>-></span> <span>bool</span><span>:</span> <span>return</span> <span>len</span><span>(</span><span>set</span><span>(</span><span>nums</span><span>))</span> <span>!=</span> <span>len</span><span>(</span><span>nums</span><span>)</span>class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(set(nums)) != len(nums)
Enter fullscreen mode Exit fullscreen mode
It’s now time to take a breath.
Let’s look at NeetCode’s solution:
<span>class</span> <span>Solution</span><span>:</span><span>def</span> <span>containsDuplicate</span><span>(</span><span>self</span><span>,</span> <span>nums</span><span>:</span> <span>List</span><span>[</span><span>int</span><span>])</span> <span>-></span> <span>bool</span><span>:</span><span>hashset</span> <span>=</span> <span>set</span><span>()</span><span>for</span> <span>n</span> <span>in</span> <span>nums</span><span>:</span><span>if</span> <span>n</span> <span>in</span> <span>hashset</span><span>:</span><span>return</span> <span>True</span><span>hashset</span><span>.</span><span>add</span><span>(</span><span>n</span><span>)</span><span>return</span> <span>False</span><span>class</span> <span>Solution</span><span>:</span> <span>def</span> <span>containsDuplicate</span><span>(</span><span>self</span><span>,</span> <span>nums</span><span>:</span> <span>List</span><span>[</span><span>int</span><span>])</span> <span>-></span> <span>bool</span><span>:</span> <span>hashset</span> <span>=</span> <span>set</span><span>()</span> <span>for</span> <span>n</span> <span>in</span> <span>nums</span><span>:</span> <span>if</span> <span>n</span> <span>in</span> <span>hashset</span><span>:</span> <span>return</span> <span>True</span> <span>hashset</span><span>.</span><span>add</span><span>(</span><span>n</span><span>)</span> <span>return</span> <span>False</span>class Solution: def containsDuplicate(self, nums: List[int]) -> bool: hashset = set() for n in nums: if n in hashset: return True hashset.add(n) return False
Enter fullscreen mode Exit fullscreen mode
The worst case is still O ( n ) O(n) O(n) , and space complexity is O ( n ) O(n) O(n) as well in the case of each element being unique.
However, I think it’s an improvement as compared to my initial solution, because instead of creating the set in one go, we can return immediately if the element is in the set as we go through adding each one.
As we have reached the end of this meditation, we can take one more deep breath. Next up is the Valid Anagram problem. Until then, happy coding.
LeetCode Meditations (79 Part Series)
1 LeetCode Meditations: Introduction
2 LeetCode Meditations — Chapter 1: Arrays & Hashing
… 75 more parts…
3 LeetCode Meditations: Contains Duplicate
4 LeetCode Meditations: Valid Anagram
5 LeetCode Meditations: Two Sum
6 LeetCode Meditations: Group Anagrams
7 LeetCode Meditations: Top K Frequent Elements
8 LeetCode Meditations: Product of Array Except Self
9 LeetCode Meditations: Longest Consecutive Sequence
10 LeetCode Meditations — Chapter 2: Two Pointers
11 LeetCode Meditations: Valid Palindrome
12 LeetCode Meditations: 3Sum
13 LeetCode Meditations: Container with Most Water
14 LeetCode Meditations — Chapter 3: Sliding Window
15 LeetCode Meditations: Best Time to Buy and Sell Stock
16 LeetCode Meditations: Longest Substring without Repeating Characters
17 LeetCode Meditations: Longest Repeating Character Replacement
18 LeetCode Meditations: Minimum Window Substring
19 LeetCode Meditations — Chapter 4: Stack
20 LeetCode Meditations: Valid Parentheses
21 LeetCode Meditations — Chapter 5: Binary Search
22 LeetCode Meditations: Find Minimum in Rotated Sorted Array
23 LeetCode Meditations: Search in Rotated Sorted Array
24 LeetCode Meditations — Chapter 6: Linked Lists
25 LeetCode Meditations: Reverse Linked List
26 LeetCode Meditations: Merge Two Sorted Lists
27 LeetCode Meditations — Interlude: Fast & Slow Pointers
28 LeetCode Meditations: Reorder List
29 LeetCode Meditations: Remove Nth Node From the End of List
30 LeetCode Meditations: Linked List Cycle
31 LeetCode Meditations: Merge K Sorted Lists
32 LeetCode Meditations — Chapter 7: Trees
33 LeetCode Meditations: Invert Binary Tree
34 LeetCode Meditations: Maximum Depth of Binary Tree
35 LeetCode Meditations: Same Tree
36 LeetCode Meditations: Subtree of Another Tree
37 LeetCode Meditations: Lowest Common Ancestor of a Binary Search Tree
38 LeetCode Meditations: Binary Tree Level Order Traversal
39 LeetCode Meditations: Validate Binary Search Tree
40 LeetCode Meditations: Kth Smallest Element in a BST
41 LeetCode Meditations: Construct Binary Tree from Preorder and Inorder Traversal
42 LeetCode Meditations: Binary Tree Maximum Path Sum
43 LeetCode Meditations: Serialize and Deserialize Binary Tree
44 LeetCode Meditations — Chapter 8: Heap/Priority Queue
45 LeetCode Meditations: Find Median from Data Stream
46 LeetCode Meditations — Chapter 9: Backtracking
47 LeetCode Meditations: Combination Sum
48 LeetCode Meditations: Word Search
49 LeetCode Meditations — Chapter 10: Tries
50 LeetCode Meditations: Implement Trie (Prefix Tree)
51 LeetCode Meditations: Design Add and Search Words Data Structure
52 LeetCode Meditations: Word Search II
53 LeetCode Meditations — Chapter 11: Graphs
54 LeetCode Meditations: Number of Islands
55 LeetCode Meditations: Clone Graph
56 LeetCode Meditations: Pacific Atlantic Water Flow
57 LeetCode Meditations: Course Schedule
58 LeetCode Meditations — Chapter 12: Dynamic Programming
59 LeetCode Meditations: Climbing Stairs
60 LeetCode Meditations: House Robber
61 LeetCode Meditations: House Robber II
62 LeetCode Meditations: Longest Palindromic Substring
63 LeetCode Meditations: Palindromic Substrings
64 LeetCode Meditations: Decode Ways
65 LeetCode Meditations: Coin Change
66 LeetCode Meditations: Maximum Product Subarray
67 LeetCode Meditations: Word Break
68 LeetCode Meditations: Longest Increasing Subsequence
69 LeetCode Meditations — Chapter 13: Intervals
70 LeetCode Meditations: Insert Interval
71 LeetCode Meditations: Merge Intervals
72 LeetCode Meditations: Non-overlapping Intervals
73 LeetCode Meditations — Chapter 14: Bit Manipulation
74 LeetCode Meditations: Number of 1 Bits
75 LeetCode Meditations: Counting Bits
76 LeetCode Meditations: Reverse Bits
77 LeetCode Meditations: Missing Number
78 LeetCode Meditations: Sum of Two Integers
79 LeetCode Meditations: Conclusion
暂无评论内容