0

I recently had an interview which consisted of following problem. Please help with possible solutions.

Write a method in Java to find duplicate elements in an integer array without using nested loops ( for/ while / do while, etc ) and without using library functions or standard API's.

6
  • 2
    What was your attempt? (Hint use recu.....) Commented Jul 18, 2015 at 6:35
  • can you use collection framework?arraylist? Commented Jul 18, 2015 at 6:37
  • @DevChoudhary Did the interviewer say you can't use loops at all or just that you can't nest loops? Commented Jul 18, 2015 at 6:51
  • Very similar: stackoverflow.com/questions/14944458/… Commented Jul 18, 2015 at 7:04
  • 1
    How is this a duplicate of the question indicated above? This question asks for all duplicate elements, the question tagged as duplicate asks only for an element. Very clear distinction between the two. Commented Jul 19, 2015 at 8:15

1 Answer 1

1

Hey the below solution has complexity O(n) and works fine. Check if it helps.

public class Main {
    public static void main(String[] args) {
        int a[] = new int[]{10,3,5,10,5,4,6};
        String distinctElement="";
        String repetitiveTerms="";
        for(int i=0;i<a.length;i++){
            if(i==0){
                distinctElement+=a[i]+" ";
            }
            else if(distinctElement.contains(""+a[i])){
                repetitiveTerms+=a[i]+" ";
            }
            else{
                distinctElement+=a[i]+" ";
            }
        }

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

13 Comments

What part of without using nested loops ( for/ while / do while, etc ) said that you could use loops?
It's not much of a challenge if you can use loops. My understanding of the question is that you can't use loops. Let's wait for the OP to clarify.
i think loops are allowed but not nested
Ok that's fine but "NESTED" is clear to us right. So you should not downgrade the answers unless you are sure about it
@Fast Snail : No it won't be problem. If you will see the code carefully i have inserted spaces between the elements so 1 0 cannot be 10. I hope this clarifies.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.