Time complexity of set in Java -
can tell me time complexity of below code?
a
array of int.
set<integer> set = new hashset<integer>(); (int = 0; < a.length; i++) { if (set.contains(arr[i])) { system.out.println("hello"); } set.add(arr[i]); }
i think o(n), i'm not sure since using set
, contains methods well. calling add
method of set
.
can confirm , explain time complexity of entire above code is? also, how space take?
i believe o(n) because loop on array, , contains
, add
should constant time because hash based set. if not hash based , required iteration on entire set lookups, upper bound n^2.
integers immutable, space complexity 2n, believe simplifies n, since constants don't matter.
if had objects in array , set, have 2n references , n objects, @ 3n, still linear (times constant) space constraints.
edit-- yep "this class offers constant time performance basic operations (add, remove, contains , size), assuming hash function disperses elements among buckets."
see here.
Comments
Post a Comment