Hopefully while filling out your taxes you didn't run in to any issues with duplicate numbers. However, if you did now is your chance to make up for it. For today's problem you'll be passed in an array of integers and asked to identify all the duplicate numbers.
For a bonus solve it in under O(n^2) without making use of a set/hash (unless you want to implement your own :)).
Comments:
Hueho - 10 years, 8 months ago
This problem is made easier by the fact that we are dealing with integers, which are ordered.
So we just need to sort the array, and scan it in a single pass to check for repeated elements.
Simple code in JavaScript:
It will perform under O(n2) as long as the sort is under O(n2) as well.
reply permalink
Carlos - 10 years, 8 months ago
The sort is O(n log(n)) according to javadoc, it does show several times if a number is duplicated more than once but, that could easily be saved with a storing array and a simple if, and display the numbers at the end.
reply permalink
Me and myself - 10 years, 8 months ago
Quicksort O(n log n)
and check if the next number is equals :)
reply permalink
Jt - 10 years, 8 months ago
C#, not sure what O it is. I did a small amount of reading and there seems to be some complexities to how Linq handles it under the scenes. I will have to do some more research later.
reply permalink
Pufe - 10 years, 8 months ago
bash one-liner:
sort input.txt | uniq -d
reply permalink
Jt - 10 years, 8 months ago
Nice
reply permalink
Adam - 10 years, 8 months ago
This is quite nice in Haskell:
reply permalink
Mre64 - 10 years, 6 months ago
/* Mre64 6/13/14
*/ import java.util.ArrayList; import java.util.LinkedList;
public class DuplicateNumber { //create an ArrayList which holds the values to be tested for duplicates private static ArrayList<Integer> holdValues = new ArrayList<Integer>();
}
reply permalink
Mre64 - 10 years, 6 months ago
without comments and a filled data set
import java.util.ArrayList; import java.util.LinkedList;
public class DuplicateNumber { private static ArrayList<Integer> holdValues = new ArrayList<Integer>(); public static void main(String[] args) { Sort(holdValues); } static void Sort(ArrayList<Integer> input){ LinkedList<Integer> copy = new LinkedList<Integer>(); for(int i : holdValues){ copy.add(i); } while(!copy.isEmpty()){ int store = copy.get(0); copy.removeFirst(); if(copy.contains(store)) System.out.println(store); } } }
reply permalink