Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Explanation: [9,4] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 1000Follow up:
nums1's size is small compared to nums2's size? Which algorithm is better?nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?Problem summary: Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Two Pointers · Binary Search
[1,2,2,1] [2,2]
[4,9,5] [9,4,9,8,4]
intersection-of-two-arrays)find-common-characters)find-the-difference-of-two-arrays)choose-numbers-from-two-arrays-in-range)intersection-of-multiple-arrays)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #350: Intersection of Two Arrays II
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
int[] cnt = new int[1001];
for (int x : nums1) {
++cnt[x];
}
List<Integer> ans = new ArrayList<>();
for (int x : nums2) {
if (cnt[x]-- > 0) {
ans.add(x);
}
}
return ans.stream().mapToInt(Integer::intValue).toArray();
}
}
// Accepted solution for LeetCode #350: Intersection of Two Arrays II
func intersect(nums1 []int, nums2 []int) (ans []int) {
cnt := map[int]int{}
for _, x := range nums1 {
cnt[x]++
}
for _, x := range nums2 {
if cnt[x] > 0 {
ans = append(ans, x)
cnt[x]--
}
}
return
}
# Accepted solution for LeetCode #350: Intersection of Two Arrays II
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
cnt = Counter(nums1)
ans = []
for x in nums2:
if cnt[x]:
ans.append(x)
cnt[x] -= 1
return ans
// Accepted solution for LeetCode #350: Intersection of Two Arrays II
use std::collections::HashMap;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let mut cnt = HashMap::new();
for &x in &nums1 {
*cnt.entry(x).or_insert(0) += 1;
}
let mut ans = Vec::new();
for &x in &nums2 {
if let Some(count) = cnt.get_mut(&x) {
if *count > 0 {
ans.push(x);
*count -= 1;
}
}
}
ans
}
}
// Accepted solution for LeetCode #350: Intersection of Two Arrays II
function intersect(nums1: number[], nums2: number[]): number[] {
const cnt: Record<number, number> = {};
for (const x of nums1) {
cnt[x] = (cnt[x] || 0) + 1;
}
const ans: number[] = [];
for (const x of nums2) {
if (cnt[x]-- > 0) {
ans.push(x);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.