878825. Check for Disjoint

Easy

Check for Disjoint Sets or Arrays

Difficulty: Easy

Slug: check-for-disjoint-sets-or-arrays

Id: 878825

Summary

The problem "Check for Disjoint" involves determining whether two given arrays are disjoint. A set of elements is considered disjoint if it contains no common elements with another set. In this problem, we need to write an algorithm that checks if the given arrays contain any common elements.

Detailed Explanation

To solve this problem, we can use a simple approach by iterating through each element in both arrays and checking for any common elements. If we find any common elements, we know the arrays are not disjoint and return false. If we don't find any common elements after checking all elements, we know the arrays are disjoint and return true.

Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers, i and j, to the start of both arrays.
  2. Iterate through both arrays until one array is exhausted:
    • For each element in the first array, check if it exists in the second array by iterating through the second array using a pointer k.
    • If an element is found in the second array, return false because the arrays are not disjoint.
    • If no common elements are found after checking all elements in both arrays, return true because the arrays are disjoint.

Here's a diagram illustrating this approach:

  Array 1: [a, b, c]
  Array 2: [d, e, f]

  i = 0, j = 0
  |       |
  |   a    |
  |       |
  k = 0, check if a exists in array 2 (no)
  i = 1, j = 0
  |       |
  |   b    |
  |       |
  k = 0, check if b exists in array 2 (no)
  i = 2, j = 0
  |       |
  |   c    |
  |       |
  k = 0, check if c exists in array 2 (no)

  No common elements found. Return true.

Time complexity: O(n + m), where n and m are the sizes of the arrays. Space complexity: O(1) because we only use a few extra variables.

Optimized Solutions

Java

View on GeeksforGeeks
public boolean checkDisjoint(int[] arr1, int[] arr2) {
    for (int i = 0; i < arr1.length; i++) {
        for (int j = 0; j < arr2.length; j++) {
            if (arr1[i] == arr2[j]) {
                return false;
            }
        }
    }
    return true;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.