881888. Find element in Set using Count

Easy

Find Element in Set using Count

Summary

Given a set and an integer target, write an algorithm to find if the target element exists in the set. The goal is to use the count function provided by the Standard Template Library (STL) to efficiently solve this problem.

Detailed Explanation

The approach is straightforward: iterate through the set using the count function to check how many times each element appears in the set. If the target element's count is greater than 0, it exists in the set; otherwise, it doesn't.

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

  1. Initialize an empty iterator for the set.
  2. Iterate through the set using the count function, which returns the number of times each element appears in the set.
  3. Compare the count of the target element to 0. If it's greater than 0, return true (i.e., the element exists in the set).
  4. If the loop completes without finding the target element, return false.

Time complexity: O(n), where n is the size of the set. This is because we need to iterate through the entire set to count each element. Space complexity: O(1), as we only use a constant amount of space to store the iterator and temporary variables.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Set;
import java.util.HashSet;

public boolean findElementInSet(Set<Integer> set, int target) {
    return set.count(target) > 0;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.