/**
 * Given two arrays, find the common elements between them.
 *
 * @param arr1 The first array (list of integers)
 * @param arr2 The second array (list of integers)
 * @return A list of common elements found in both arrays
 */
fun findCommonElements(arr1: List<Int>, arr2: List<Int>): List<Int> {

    // Remove duplicates and sort the arrays to optimize the intersection process
    val sortedArr1 = arr1.toSet().sorted()
    val sortedArr2 = arr2.toSet().sorted()

    // Initialize variables
    val commonElements = mutableListOf<Int>()
    var i = 0
    var j = 0

    while (true) {
        // Check if any of the arrays have been fully traversed
        if (i >= sortedArr1.size || j >= sortedArr2.size) {
            break
        }

        // Compare the current elements in both arrays
        when {
            sortedArr1[i] == sortedArr2[j] -> {
                commonElements.add(sortedArr1[i])
                i++
                j++
            }
            sortedArr1[i] < sortedArr2[j] -> i++
            else -> j++
        }
    }

    return commonElements
}
/**
 * Given two arrays, find the common elements between them.
 *
 * @param arr1 The first array (list of integers)
 * @param arr2 The second array (list of integers)
 * @return A list of common elements found in both arrays
 */
fun findCommonElements(arr1: List<Int>, arr2: List<Int>): List<Int> {
/**
 * Given two arrays, find the common elements between them.
 *
 * @param arr1 The first array (list of integers)
 * @param arr2 The second array (list of integers)
 * @return A list of common elements found in both arrays
 */
fun findCommonElements(arr1: List<Int>, arr2: List<Int>): List<Int> {

    // Remove duplicates and sort the arrays to optimize the intersection process
    val sortedArr1 = arr1.toSet().sorted()
    val sortedArr2 = arr2.toSet().sorted()

    // Initialize variables
    val commonElements = mutableListOf<Int>()
    var i = 0
    var j = 0

    while (true) {
        // Check if any of the arrays have been fully traversed
        if (i >= sortedArr1.size || j >= sortedArr2.size) {
            break
        }

        // Compare the current elements in both arrays
        when {
            sortedArr1[i] == sortedArr2[j] -> {
                commonElements.add(sortedArr1[i])
                i++
                j++
            }
            sortedArr1[i] < sortedArr2[j] -> i++
            else -> j++
        }
    }

    return commonElements
}