2dbi

Check if Two Lists Have Equal Content

viaLeetCode

Problem Given two integer lists (possibly unsorted), determine whether they hold the same content as multisets — same values with same counts. Then extend to lists of custom objects.

Input / Output

  • Input: two lists. Output: boolean.

Constraints

  • Sizes up to 10^5; O(n) expected via hashing; duplicates must be respected (set comparison is wrong).

Example

  • [1,2,2,3] vs [3,2,1,2] → true; [1,2,2] vs [1,1,2] → false.

Expected approach

  • Size check, then frequency map: count first list, decrement per second-list element, fail on underflow/missing — O(n) time and space. Sorting both and comparing is the O(n log n) alternative. The custom-object follow-up is the real test: HashMap correctness requires overriding BOTH equals() and hashCode() consistently (equal objects → equal hashes); with only equals overridden the map treats logically-equal objects as distinct. Comparable/Comparator needed instead for the sorting route.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account