I had the below problem in a coding test and I got 28/30 tests passes and 2 failed due to a time-out.
Problem
You have created a programming language and now you have decided to addhashmap
support to it. It was found that in common programming languages, it is impossible to add a number to allhashmap
keys/values. So, you have decided to implement your ownhashmap
in your new language with following operations.
insert x y
- insert and object with keyx
and valuey
get x
- return the value of an object with keyx
addToKey x
- addx
to all keys in mapaddToValue y
- addy
to all values in mapYour task is to implement this
hashmap
, apply the given queries, and to find the sum of all the results forget
operations
For Example
- For
queryType=["insert","insert","addToValue","addToKey","get"]
andquery=[[1,2],[2,3],[2],[1],[3]]
, the output should behashMap(queryType,query)=5
.
Explanation
insert 1 2
- hashmap will be{1:2}
insert 2 3
- hashmap will be{1:2,2:3}
addToValue 2
- hashmap will be{1:4,2:5}
addToKey 1
- hashmap will be{2:4,3:5}
get 3
- value is 5
Input/Output
- [execution time limit] 3 seconds (Java)
- [input] array.string queryType
Array of query types. its is guaranteed that eachqueryType[i]
any one of the above mentioned operation
1<=queryType.length<=10^5- [input] array.array.integer query
Array of queries, where each query is mentioned by 2 numbers for insert and one number for others Key values are in range [-10^9,10^9]
Below is my solution in Java
long hashMap(String[] queryType, int[][] query) {
long sum = 0;
Integer currKey = 0;
Integer currValue = 0;
Map<Integer, Integer> values = new HashMap<>();
for (int i = 0; i < queryType.length; i++) {
String currQuery = queryType[i];
switch (currQuery) {
case "insert":
HashMap<Integer, Integer> copiedValues = new HashMap<>();
if (currKey != 0 || currValue != 0) {
Set<Integer> keys = values.keySet();
for (Integer key : keys) {
copiedValues.put(key + currKey, values.get(key) + currValue);
}
values.clear();
values.putAll(copiedValues);
currValue = 0;
currKey = 0;
}
values.put(query[i][0], query[i][1]);
break;
case "addToValue":
currValue += values.isEmpty() ? 0 : query[i][0];
break;
case "addToKey":
currKey += values.isEmpty() ? 0 : query[i][0];
break;
case "get":
copiedValues = new HashMap<>();
if (currKey != 0 || currValue != 0) {
Set<Integer> keys = values.keySet();
for (Integer key : keys) {
copiedValues.put(key + currKey, values.get(key) + currValue);
}
values.clear();
values.putAll(copiedValues);
currValue = 0;
currKey = 0;
}
sum += values.get(query[i][0]);
}
}
return sum;
}
Is there any other data structure I can use instead of hashmap
or Can I improve my code to be more linear?
Map
every time you makeinsert
orget
queries, if you can explain me why I appreciate it. \$\endgroup\$get(7)
afteraddToKey(4)
andaddToKey(1)
meansinternalMap.get(7-(4+1))
. And than create a solution. \$\endgroup\$