OOP Fundamentals · Coding problem

Make HashSet Recognize Equal Values

A free coding problem from the equals, hashCode & Object Contracts skill. Read it here, then solve it in the app in Java or Python.

  • Easy
  • Coding problem
  • Free
  • Java and Python

The problem

Right now two Point(1, 2) objects are "different" - Java's default equals compares identity - so the set keeps duplicates and can't find points that are clearly in it.

Override equals and hashCode in both classes:

  • Point - equal when x and y are equal
  • Tag - equal when the names match ignoring case ("Java" equals "JAVA"). Remember: equal objects must have equal hash codes, so the hash must ignore case too.

In Python: override __eq__ and __hash__. Python's default compares identity too - and a class that defines __eq__ without __hash__ becomes unhashable, so it can't go in a set at all.

Commands: POINT <x> <y> (add, print set size), HAS <x> <y>, TAG <name> (add, print set size), HASTAG <name>.

Example

Input:
5
POINT 1 2
POINT 1 2
HAS 1 2
TAG Java
HASTAG JAVA

Output:
points 1
points 1
has point true
tags 1
has tag true

Constraints

  • At most 1000 commands; coordinates fit in an int; tag names are ASCII letters.

How it's graded

  • Run checks your code against the examples. Submit also runs hidden tests, and you see pass or fail for them, never their inputs.
  • Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
  • Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.

More problems in equals, hashCode & Object Contracts

Solve it Make HashSet Recognize Equal Values free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime