Insert the final 2Reading index 3 inserts 2, producing the complete distinct set {4,1,2}.
401142set reads23
inputLength4setSize3actioninsert 2
saved state4one set entry1one set entry2one set entry
Compare the two lengthslen(nums)=4 and len(set(nums))=3; because 4 != 3, the function returns true.
401142set reads23
inputLength4comparison4 != 3resulttrue
saved state4one set entry1one set entry2one set entry
Recognize it
Use a set when the question asks whether any equality collision exists and the values themselves, not their positions or counts, determine duplication.
Keep true
After set construction has consumed a prefix, the set contains exactly one entry for every distinct value in that prefix, so its size grows only on first occurrences.
Reuse it
When only uniqueness matters, canonicalize values into a set and compare cardinality; retain counts or positions only when the follow-up question actually needs them.
Read it this way: For nums=[4,1,4,2], set(nums) begins empty before reading index 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Pattern: Set.
Simple idea: A set removes repeated values. A duplicate exists when the set is shorter
than the input.