What is the easiest/simplest/most efficient way to detect if a 2D array has duplicate/repeating values?
e.g. 2D Array:
{{2, 17, 4, 5} {3, 2, 34 9}}
This matrix has multiple "2" values.
I want to set a boolean to true if this is the case.
Thanks in advance!
1 Answer 1
I think the best you can do here is O(n) because you won't know if the very last element is a duplicate until you check it. Here's an idea:
Have a Set
of values. Iterate the 2d array and for each element do this:
if (!set.add(element))
// a duplicate was found!
This works because Set.add returns "true if this set did not already contain the specified element"
-
2Wouldn't it be sufficient with a
Set
?if (set.contains(value))
then there's a duplicate, otherwise add the value to the set. (The fact that the standard HashSet implementation use an underlying HashMap is another matter...)Simon Forsberg– Simon Forsberg2013年09月10日 00:16:39 +00:00Commented Sep 10, 2013 at 0:16 -
I'm a little confused where you got the "1". And it seems nice, but my issue is this is a "lab" for school so it has to use a 2D array.Connor– Connor2013年09月10日 00:17:12 +00:00Commented Sep 10, 2013 at 0:17
-
@SimonAndréForsberg Yeah good point. That's a better solutionDaniel Kaplan– Daniel Kaplan2013年09月10日 00:17:22 +00:00Commented Sep 10, 2013 at 0:17
-
@Connor You will have to loop through the array in one way or another. Our suggestion is that you add each value you encounter to a HashSet if it doesn't already exists in it - if it already exists in the set, well then you have found a duplicate.Simon Forsberg– Simon Forsberg2013年09月10日 00:27:38 +00:00Commented Sep 10, 2013 at 0:27
-
1@SimonAndréForsberg updated. My brain went to
Map
first because I was reminded of a similar interview question I asked where someone asked the quickest way to get the number of duplicates. ASet
doesn't help with that.Daniel Kaplan– Daniel Kaplan2013年09月10日 00:32:10 +00:00Commented Sep 10, 2013 at 0:32
Explore related questions
See similar questions with these tags.
{2,3,2,1}
?