Skip to content

Instantly share code, notes, and snippets.

@svlada
Last active December 15, 2015 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svlada/5280584 to your computer and use it in GitHub Desktop.
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’.”
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