Leetcode: Number of Good Pairs (Kotlin)
Kotlin

Leetcode: Number of Good Pairs (Kotlin)

2024-03-20
10 min read

Leetcode: Number of Good Pairs

The Number of Good Pairs is an easy array problem on Leetcode. Number of Good Pairs - LeetCode

Problem Statement

Understanding the Problem

The problem wants you to count all the times a number appears before itself in the array. In the problem, i refers to an earlier index the number appears, and j refers to a later index where the number appears. Only focus on counting a matching number after its current index.

Examples

Constraints

Brute Force Approach

A brute force approach would be to use a nested loop to count each time a number appears after it. Of course, this is inefficient for a large array size with time complexity O(n)².

A Better Approach

A more efficient approach would be to use a frequency array.

  1. Create an array that we can use to store the count of each number in our original array.

  2. Loop through the original array. In each iteration of the loop, use the number as the index for the frequency array (frequencyArray[num]), and add that to the count.

  3. Also, in each iteration, increment that same number (frequencyArray[num]) in the array. Every time you find this number, you can update the count easily.

Java Solution:

{% gist https://gist.github.com/cmcoffeedev/37fc4a81d95c0e6b8451677b88b34a9c.js %}

Kotlin Solution:

{% gist https://gist.github.com/cmcoffeedev/9833466393e8814465c59a85cc4f744c.js %}