You get two arrays of whole numbers, nums1 and nums2. Return every value that shows up in both of them.
Each such value goes into the answer once, however many times it repeats in either array. The values can be returned in any order.
Example 1
Input: nums1 = [3, 7, 3, 5], nums2 = [5, 1, 5, 3, 8] Output: [5, 3] Why: 3 and 5 are in both; [3, 5] is also accepted
2 more examples and the constraints
Example 2
Input: nums1 = [6, 2], nums2 = [4, 8] Output: [] Why: no value is shared
Example 3
Input: nums1 = [9, 9, 9], nums2 = [9] Output: [9] Why: 9 is shared, and it is listed once
Constraints
- 1 ≤ length of nums1, length of nums2 ≤ 1,000
- 0 ≤ every value ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan for every valueO(n·m)
- Sort + two pointersO(n log n + m log m)
- Hash setO(n + m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 values in each array | Verdict |
|---|---|---|---|
| Scan for every value | O(n·m) | Mention it, then move on | |
| Sort + two pointers | O(n log n + m log m) | Passes; good if already sorted | |
| Hash set | O(n + m) | Best; one pass each |
n = length of nums1, m = length of nums2.
Edge cases to test
- Nothing shared. [6, 2] and [4, 8] give an empty list, not an error.
- Repeats in both arrays. [9, 9, 9] and [9, 9] still give [9] once.
- One array inside the other. If every value of nums2 is in nums1, the answer is the distinct values of nums2.
- Zero is a value. Values start at 0; do not use 0 as a "not found" marker.
Common mistakes
- Adding a shared value each time it repeats, so the result has duplicates.
- Expecting the answer in sorted or input order; any order is accepted, so tests must not assume one.
- Building sets from both arrays and then looping over the wrong one, so values only in one array slip in.
How to talk through it
- 1Clarify. Should repeats appear once? Does the order of the answer matter? How large are the arrays?
- 2Give the brute force. Scan nums2 for each value of nums1: O(n·m).
- 3Mention sorting. Sorted arrays meet in one two-pointer walk; good when memory is tight.
- 4Code the set. Set from nums1, scan nums2, remove each hit so it is reported once.
- 5Test out loud. Run a case with nothing shared and one with heavy repeats before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?