1

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!

3
  • I'm aware that I can probably loop through the entire matrix for each number but that is like 4 loop statements. Seems inefficient to me. Commented Sep 10, 2013 at 0:09
  • Can you say something more about data in your array? Can one row contain duplicate values like {2,3,2,1}? Commented Sep 10, 2013 at 0:13
  • No. No duplicates at all in the matrix. Commented Sep 10, 2013 at 0:14

1 Answer 1

3

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"

Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn'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...)
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.
@SimonAndréForsberg Yeah good point. That's a better solution
@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.
@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. A Set doesn't help with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.