3

How can we find the duplicate elements in an array with the following limitations:

  1. Without using extra memory

  2. Can use variables for storing data and not objects like HashMap/HashSet and all.

  3. Time complexity can be O(n) and should not be O(n^2)

Note :

Here array is dynamic integer array.

1
  • 4
    We cannot. Sorry. Commented Sep 9, 2017 at 3:25

2 Answers 2

1

If all elements of the array are in between [0, n), then we can do it in the following way

  1. Traverse the array from i = 0 to n
  2. for every element a[i], suppose

    x = a[i] if a[i] >= 0
    x = a[i] + n if a[i] < 0
    check if a[x] >= 0. If yes then add -n to a[x]

  3. if for another element a[i]. if a[x] < 0 then that means that a similar value changed the index hence it is a duplicate.
Sign up to request clarification or add additional context in comments.

3 Comments

But a[i] >= 0. As you stated before. So you never add n.
I am adding -n to a[x] so it can become negative
Provided solution will work only If all elements of the array are in between [0, n], if not it will throw an ArrayIndexOutOfBoundsException.
0

Below is my solution for the above question.

public static boolean checkDuplicates(int[] arr, int length) {
    int value = 0;
    boolean isDupFound = false;
    for (int i = 0; i < length; i++) {
        int currChar = arr[i];
        int bit_Position = currChar - 'a';
        if ((value & (1 << bit_Position)) > 0) {
            isDupFound = true;
            break;
        } else {
            value = value | (1 << bit_Position);
        }
    }
    return isDupFound;
}

3 Comments

That doesn't answer your own question. You wanted to find "the duplicate elements in an array", which you did not accomplish here.
Hi Gulzar.. Here we just need not to break the loop if we found the duplicate element in array and continue till all the elements in an array which will serve our purpose.
Remove the break and print all the values instead to assign to a boolean value.

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.