Array Difference
Array Difference - Explanation
Problem Summary
Write a function that returns elements in the first array but not in the second.
Go to Problem →Detailed Explanation
이 문제는 **filter와 부정 연산자(!)**를 조합하여 두 배열의 차집합을 구하는 방법을 학습합니다. ## 핵심 개념: 집합 연산 - 차집합 차집합은 첫 번째 집합에는 있지만 두 번째 집합에는 없는 요소들의 집합입니다. ### 접근 방법 ```javascript arr1.filter(x => !arr2.includes(x)) ``` - arr1의 각 요소에 대해 - arr2에 포함되어 있지 않은지 확인 (!) - 포함되지 않은 요소만 남김 ### 교집합과의 차이 ```javascript // 교집합: 둘 다 포함 arr1.filter(x => arr2.includes(x)) // 차집합: 첫 번째에만 포함 arr1.filter(x => !arr2.includes(x)) ``` ### 대칭 차집합 양쪽에만 있는 요소들 (XOR 연산): ```javascript const diff1 = arr1.filter(x => !arr2.includes(x)); const diff2 = arr2.filter(x => !arr1.includes(x)); [...diff1, ...diff2] ``` 차집합은 데이터 비교, 변경사항 감지, 권한 체크 등에서 자주 사용됩니다.
Solution Code
function difference(arr1, arr2) {
return arr1.filter(x => !arr2.includes(x));
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n*m)
Space Complexity
O(n)
Uses memory proportional to input size