Junior — Middle
How to implement a function that finds the first element in an array missing in the second array?
sobes.tech AI
Answer from AI
To find the first element in the first array that is not in the second, you can iterate through the first array and check for each element whether it is contained in the second. Return the first mismatch.
Example in Kotlin for Android:
fun firstMissingElement(arr1: Array<Int>, arr2: Array<Int>): Int? {
val set2 = arr2.toSet() // for quick lookup
for (element in arr1) {
if (element !in set2) {
return element
}
}
return null // if all elements are in the second array
}
This approach is efficient and simple to implement.