LeetCode Entry

1512. Number of Good Pairs

3.10.2023 easy 2023 kotlin

Count equal pairs

1512. Number of Good Pairs easy blog post substack image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/358

Problem TLDR

Count equal pairs

Intuition

The naive N^2 solution will work. Another idea is to store the number frequency so far and add it to the current result.

Approach

Let’s use Kotlin’s API:

  • with
  • fold

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


    fun numIdenticalPairs(nums: IntArray) = with(IntArray(101)) {
      nums.fold(0) { r, t -> r + this[t].also { this[t]++ } }
    }