Array Element Frequency Counter

Problem Explanation: Given two arrays A and B of equal length N, write a function that returns an array C of length N where C[i] represents the number of occurrences of A[i] in array B.

Example:

Input: A = [1, 2, 3, 4, 5], B = [1, 1, 2, 2, 1] 

Output: C = [3, 2, 0, 0, 0]
Input: A = [10, 20, 30, 40, 50], B = [50, 40, 30, 20, 10] 

Output: C = [1, 1, 1, 1, 1]

Expected Time and Space Complexity: O(N) time complexity and O(N) space complexity,

where N is the length of the input arrays A and B.

Constraints:

  • The length of input arrays A and B will be equal and at most 10^5.
  • The elements of the input arrays A and B will be integers between 1 and 10^9, inclusive.

Kotlin Solution :

Kotlin
fun elementFrequencyCounter(A: IntArray, B: IntArray): IntArray {
    val map = mutableMapOf<Int, Int>()
    for (b in B) {
        map[b] = map.getOrDefault(b, 0) + 1
    }
    val C = IntArray(A.size)
    for (i in A.indices) {
        C[i] = map.getOrDefault(A[i], 0)
    }
    return C
}
fun main() {
    val A = intArrayOf(1, 2, 3, 4, 5)
    val B = intArrayOf(1, 1, 2, 2, 1)
    val C = elementFrequencyCounter(A, B)
    println(C.contentToString())
    // Output: [3, 2, 0, 0, 0]
    
    val D = intArrayOf(10, 20, 30, 40, 50)
    val E = intArrayOf(50, 40, 30, 20, 10)
    val F = elementFrequencyCounter(D, E)
    println(F.contentToString())
    // Output: [1, 1, 1, 1, 1]
}

Leave a Comment