Last active
December 15, 2015 15:19
-
-
Save svlada/5280584 to your computer and use it in GitHub Desktop.
Answer to question from http://victorhurdugaci.com/my-interview-with-microsoft/ “You are given two arrays: before: {3, 3, 5, 8, 1} and after: {5, 3, 2, 4}. Determine what numbers were removed/added from/to the ‘before’ array in order to obtain ‘after’.”
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
public class BeforeAfterArray { | |
public static void main(String[] args) { | |
int [] before = {3, 3, 5, 8, 1}; | |
int [] after = {3, 3, 3, 3}; | |
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); | |
for (int i = 0; i < before.length; i++) { | |
int key = before[i]; | |
int value = map.containsKey(key) ? map.get(key) + 1 : 1; | |
map.put(key, value); | |
} | |
for (int i = 0; i < after.length; i++) { | |
int key = after[i]; | |
if (map.containsKey(key)) { | |
map.put(key, map.get(key) - 1); | |
if (map.get(key) < 0) { | |
System.out.println("Element " + key + " is added to resulting array."); | |
} | |
} else { | |
System.out.println("Element " + key + " is added to resulting array."); | |
} | |
} | |
for (Map.Entry<Integer, Integer> entry : map.entrySet()) { | |
if (entry.getValue() > 0) { | |
System.out.println("Element " + entry.getKey() + " is removed from resulting array."); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment