Problem 271439 · easy · Level 02 Linear Data Structures

Twin Readings

hash maps · counting · pair counting

Given a list nums, count the index pairs (i, j) with i < j and nums[i] == nums[j].

Examples

Input:  nums = [2, 2, 2, 5, 5]
Output: 4
Explanation: three pairs of 2s (0,1), (0,2), (1,2) and one pair of 5s (3,4).

Input:  nums = [1, 2, 3]
Output: 0

Constraints

  • 0 <= len(nums) <= 10**5
  • The answer can exceed 2**31; Python ints are fine.
  • Target complexity: O(n) time. A double loop is too slow.

Goals

  • Count pairs without a nested loop
  • Use the count-so-far trick while scanning
Starting Python…