2 Likes

Domino Rotation

``````public int solution(int[] A, int[] B) {
// write your code in Java SE 8
if(A.length==0 && B.length==0)
return 0;
if(A.length==0 || B.length==0)
return -1;
return minDominoRotations(A, B);

}
public int minDominoRotations(int[] A, int[] B) {
int n = A.length;
int rotations = check(A[0], B, A, n);
if (rotations != -1 || A[0] == B[0]) return rotations;
else return check(B[0], B, A, n);
}
public int check(int x, int[] A, int[] B, int n) {
int rotations_a = 0, rotations_b = 0;
for (int i = 0; i < n; i++) {
if (A[i] != x && B[i] != x) return -1;
else if (A[i] != x) rotations_a++;
else if (B[i] != x) rotations_b++;
}
return Math.min(rotations_a, rotations_b);
}
``````

``````public int solution(String[] emails) {
// write your code in Java SE 8
HashMap<String, Integer> hs = new HashMap();
for(String email: emails){
StringBuilder sb = new StringBuilder();
int at_index = email.indexOf("@");
int plus_index = email.indexOf("+");
if(plus_index == -1){
sb.append(email.substring(0,at_index).replace(".", ""));
}else{
sb.append(email.substring(0,plus_index).replace(".", ""));
}
sb.append(email.substring(at_index));
String s = sb.toString();
hs.put(s,hs.getOrDefault(s,0)+1);
}
int max = 0;
//String maxs = "";
for(String key: hs.keySet()){
if(hs.get(key) > max){
max = hs.get(key);
//maxs = key;
}
}
return max;
}
``````

Lottery Coupons

``````public int solution(int[] coupons) {
// write your code in Java SE 8
HashMap<Integer, Integer> hm = new HashMap();
int price = Integer.MAX_VALUE;
for(int i = 0; i<coupons.length; i++){
int c = coupons[i];
if(hm.containsKey(c)){
price = Math.min(price, i-hm.get(c) + 1);
}
hm.put(c,i);
}
return price == Integer.MAX_VALUE ? -1 : price;
}
``````