programming_class_cheats icon indicating copy to clipboard operation
programming_class_cheats copied to clipboard

Use a set instead of a list, and a copy of it to count `(i, j)` and `(j, i)` once.

Open ghost opened this issue 4 years ago • 0 comments

This solution is merely for convenience and is neither memory nor time-efficient:

  • Lookups are O(n) in lists and O(1) in dictionaries and sets (because dictionaries and sets are implemented as hash tables). I used a set because we don't need to associate values (and also sets use less memory than dictionaries).

  • To count (i, j) and (j, i) once, I look up j in a copy of the set numbers (instead of the numbers itself), and then delete i from the copy. This way when i:=j, we won't find j:=i in the copy so it doesn't count. Also, we can't modify the set while we're iterating over it, and numbers have to reset for each time we call func(x) (these are other reasons I used a copy).

ghost avatar Sep 22 '21 11:09 ghost