Menu
Coddy logo textTech

Set Operations

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 13 of 63.

Union keeps members found in either set, intersection keeps shared members, and subtraction keeps members of the first set absent from the second. These operations return new sets; subtraction depends on operand order.

Inside main:

val a = setOf(1, 2, 3)
val b = setOf(2, 4)
println(a.intersect(b).sorted())

Only two occurs in both sets.

Intersection keeps shared members; subtraction is directional.

challenge icon

Challenge

Medium

Complete sharedItems with parameters first: List<Int>, second: List<Int>. Return distinct integers appearing in both inputs, sorted ascending.

Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.

Return a value of type List<Int>. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.

Try it yourself

fun sharedItems(first: List<Int>, second: List<Int>): List<Int> {
    // Write your solution here.
    return emptyList()
}
fun main() {
    val firstCount = readln().toInt()
    val first = mutableListOf<Int>()
    for (i0 in 0 until firstCount) {
        val firstItem = readln().toInt()
        first.add(firstItem)
    }
    val secondCount = readln().toInt()
    val second = mutableListOf<Int>()
    for (i0 in 0 until secondCount) {
        val secondItem = readln().toInt()
        second.add(secondItem)
    }
    println(sharedItems(first, second))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground