Akamai Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
Instead of Using Hashmap we can sort the list and count the second number.
func secondNumber(arr []int) int {
var sec_count int
var same_num int
sort.Ints(arr)
for i := 0; i < len(arr)-1; i++ {
fmt.Println(arr[i], sec_count, arr[i])
if arr[i] == arr[i+1] {
if sec_count == 1 && arr[i] != same_num {
return arr[i]
} else {
sec_count += 1
same_num = arr[i]
}
}
}
return -1
}
def secDuplicate(li):
first = None
sec = None
for i, val in enumerate (li):
if val in li [i+1:]:
if first == None:
first = val
else:
sec = val
break
return (first, sec)
testCases = {"no_dups": [1,7,19,8,6,5,9,2, 3], "one_dup": [5,6,3,2,1,1,9], "two_dups": [2,1,3,1,5,2,7]}
for k, li in testCases.items():
print (k, li, secDuplicate (li))
no_dups [1, 7, 19, 8, 6, 5, 9, 2, 3] (None, None)
one_dup [5, 6, 3, 2, 1, 1, 9] (1, None)
two_dups [2, 1, 3, 1, 5, 2, 7] (2, 1)
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class DuplicateValues {
public static void main(String[] args) {
int[] arr={2,3,4,5,7,2,4,7};
Integer c=1;
HashMap hp =new HashMap();
for (int i =0;i<arr.length;i++){
if(hp.containsKey(arr[i])){
c= (Integer) hp.get(arr[i]);
hp.put(arr[i], c+1);
} else
hp.put(arr[i], c);
}
Set s = hp.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry mp = (Map.Entry)it.next();
Integer i =(Integer) mp.getValue();
if(i>1){
System.out.println(mp.getKey()+"--"+mp.getValue());
}
}
}
}
Use Hashmap while traversing through array, first element already present in hashmap is the duplicate. Sharing my solution in Python below.
Test Code
- prudent_programmer September 14, 2018