Leetcode: Number of Good Pairs (Kotlin)
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.
-
Create an array that we can use to store the count of each number in our original array.
-
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.
-
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 %}