• Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding duplicate elements in an array without using nested loops  RSS feed

 
Dev Choudhary
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I recently had an interview which consisted of following problem. Please help with possible solutions.

Write a function in Java to find duplicate elements in an integer array without using nested loops ( for/ while / do while, etc ) and without using library functions.
 
Liutauras Vilda
Sheriff
Posts: 4930
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

First of all, in Java there are no functions. More correctly would be to ask to write a program or method.

I'd say you could solve that with recursion if there's no restriction to use it.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would a Stream be permissible?

Remember in an interview it is not what you say so much as how you say it. The way you approach the question and the sort of questions you ask for clarification count as much as the actual solution you produce. Whether saying the producing such code in real life merits instant dismissal is a good idea, I am not sure.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it says no NESTED loops, right?

use a loop, and use each element as a key to map. for each one, first check to see if the key exists - if so, you have a duplicate. if not, insert it.
 
Piet Souris
Master Rancher
Posts: 2044
75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If two sets are used, and looking at the return type when you insert
an element into a set, the solution can be very short. As Fred says,
you need just one loop.

Worrying though, is this requirement:
Dev Choudhary wrote:(...) and without using library functions.

Whatever that means...

Greetz,
Piet
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!