Sets


Collapse Content

Sets are an abstract data type for holding an unordered collection of items without any duplicate values. Unlike Arrays, Sets have no specific order or index associated with each item.

These are the important methods a Set supports:

  • add(item) - Adds an item to the set.
  • remove(item) - Removes an item from the Set.
  • contains(item) - Returns true if the item is in the Set, and false otherwise.

Purpose of Sets

The Set is useful when you want to check if items are in a collection but there's no specific order that you care about. For example, let's say you're given a raw list of numbers and need to find the numbers that appear more than once. What Algorithm could you use to find them?

Solution
Create a Set for holding the items. For each item, check if it's already in the Set. If it is, you've found a duplicate. Otherwise add the item to the Set.

Standard Sets

Java provides the interface Set which defines the standard Set methods, and the HashSet is the commonly used Set Class.

(Ruby and Python also provide standard library Sets.)

Challenge

This challenge is similar to Duplicate Diamonds but contains a large range of values. Use a Set to find the answer in an optimal manner.

Challenge

A duplicate is a number whose value appeared earlier in the list. Given a list of numbers, print all the duplicates in the order that they appear. (Duplicates that appear multiple times should be printed multiple times.)

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

Contact Us
Sign in or email us at [email protected]