VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-two-given-sets-disjoint/

⇱ Check for Disjoint Arrays or Sets - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check for Disjoint Arrays or Sets

Last Updated : 4 Feb, 2026

Given two arrays a[] and b[], check if they are disjoint, i.e., there is no element common between both the arrays.

Examples:

Input: a[] = [12, 34, 11, 9, 3], b[] = [2, 1, 3, 5]
Output: False
Explanation: 3 is common in both the arrays.

Input: a[] = [12, 34, 11, 9, 3], b[] = [7, 2, 1, 5]
Output: True
Explanation: There is no common element in both the arrays.

[Naive Approach] Using Two Nested Loops - O(n * m) Time and O(1) Space

The simplest approach is to iterate through every element of the first array and search it in another array, if any element is found, the given arrays are not disjoint.


Output
True

[Better Approach] Using Sorting and Two Pointer - O(n Log n + m Log m) Time and O(1) Space

First, we sort both the arrays. Then, we initialize pointers at the beginning of both the arrays. If the value at one pointer is smaller than the value at the other, we increment that pointer. If at any point, the values at both pointers become equal, the arrays are not disjoint. If no value matches during the whole traversal, then the given arrays are disjoint.


Output
True

[Expected Approach] Using Hashing - O(n + m) Time and O(n) Space

First, we insert all elements of array a into a hash set. Then, for each element of array b, we check if it exists in the hash set. If any element from array b is found in the hash set, the arrays are not disjoint. otherwise, they are disjoint.


Output
True
Comment