📚

Array Difference

Array Difference - Explanation

보통 배열 O(n*m) O(n)

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

solution.js
function difference(arr1, arr2) {
  return arr1.filter(x => !arr2.includes(x));
}

Key Concepts from This Problem

1. filter 메서드
2. 부정 연산자
3. 차집합
4. 집합 연산

Common Mistakes

A-B와 B-A는 다른 결과입니다 - 순서가 중요합니다
!연산자 위치를 잘못 두면 의도와 다른 결과가 나옵니다
빈 배열과의 차집합은 원본 배열과 같습니다

Hints

Hint 1: filter와 !includes를 사용하세요.

Complexity Analysis

Time Complexity

O(n*m)

Space Complexity

O(n)

Uses memory proportional to input size

Related Tags

#배열 #filter #집합