Say I have two linked lists of same length.
class Node {
int val;
Node next;
}
List<Node> list1 = LinkedList<>(); // list1 has 1,2,3,4,5,6,7... N
List<Node> list2 = LinkedList<>(); // list2 has 1,2,3,4,5,6,7... N
I create a HashMap and map each element of list1 to list2
Map<Node, Node> map = new HashMap<Node, Node>();
for (int i = 0; i < list.size(); i++){
map.put(list1.get(i), list2.get(i));
}
The HashMap only inserts reference to existing data, it doesn't create any new Node. In term of memory usage, how much memory does the HashMap consume? In other words, if we talk about space complexity of this insertion (we are not counting the memory used by the list1 and list2 as extra memory), what is the space complexity? O(N) or O(1)?
O(n), regardless of how many bytes it uses per element. The complexity only tells you, how it scales, and well, storing twice the number of elements will need roughly consume twice the memory. That’s a linear dependency, also known asO(n). Besides that, there is no relationship between the map and theLinkedList, further, aNodeclass have anextreference suggests some kind of linked list that is also unrelated to theLinkedList.