878960. Check Subset

Easy

Check Subset

Summary

The problem involves checking if a given set is a subset of another set. The algorithmic approach is based on set operations, specifically the issubset method in Python or equivalent methods in other programming languages.

Detailed Explanation

The problem requires us to write an algorithm that takes two sets as input and returns True if the first set is a subset of the second set, and False otherwise. A subset is a set containing some or all elements of another set.

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

  1. Initialize a variable is_subset to True.
  2. Iterate through each element in the first set.
  3. For each element, check if it exists in the second set using the in operator.
  4. If any element from the first set is not found in the second set, set is_subset to False and break out of the loop.
  5. After iterating through all elements, return the value of is_subset.

Here's an ASCII art diagram illustrating the algorithm:

          +---------------+
          |  Iterate     |
          |  through each  |
          |  element in   |
          |  set A        |
          +---------------+
                  |
                  v
+----------------------------------------+
|  For each element, check if it exists  |
|  in set B using the 'in' operator    |
+----------------------------------------+
                  |
                  v
+----------------------------------------+
|  If any element is not found in     |
|  set B, set is_subset to False and  |
|  break out of the loop            |
+----------------------------------------+

Time complexity: O(n), where n is the size of the first set. Space complexity: O(1), as we only need a single variable is_subset to store the result.

Optimized Solutions

Java

View on GeeksforGeeks
public boolean isSubset(Set<Integer> setA, Set<Integer> setB) {
    for (int element : setA) {
        if (!setB.contains(element)) {
            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.