programming_class_cheats
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.
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 upjin a copy of the setnumbers(instead of thenumbersitself), and then deleteifrom the copy. This way wheni:=j, we won't findj:=iin the copy so it doesn't count. Also, we can't modify the set while we're iterating over it, andnumbershave to reset for each time we callfunc(x)(these are other reasons I used a copy).