Start learning free

LESSON 130 OF 348 · LOOPS & CONDITIONALS

Array Contains in Kotlin: A Linear Search with a for Loop

Practice Read the full explanation

Given an array of integers nums and another integer value, check if value occurs in nums.

If the value occurs in nums, return true; otherwise return false.


Examples:

contains([1, 2, 4, 5], 4) -> true

contains([-1, 2, -4, 0, 10], 7) -> false

Note:

Do not use builtin functions such as find() or includes(), it would defy the purpose of the challenge. Write the whole code yourself.

STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · LOOPS & CONDITIONALS

    Array Contains in Kotlin, explained

    Problem overview

    The function contains receives an IntArray named nums and an Int named value. It returns true if value appears anywhere in nums and false if it doesn't. The task forbids ready-made search helpers, so the loop is yours to write.

    Two examples show the behaviour. In [1, 2, 4, 5] the value 4 is present, so the answer is true. In [-1, 2, -4, 0, 10] the value 7 never appears, so the answer is false.

    Approach: look at every element until you find a match

    An unsorted array gives no hint about where a value might be, so the only reliable method is to inspect the elements one by one. This is a linear search. Two facts shape the code:

    • A single match is enough to answer true. There is no reason to keep looking, so the function can return immediately.
    • The answer can be false only after every element has been compared. That means the false belongs after the loop, not inside it.

    The common wrong turn is to answer false inside the loop as soon as one element differs from value. One mismatch says nothing about the elements that come later.

    Step by step

    1. Loop over the array. A for loop with a variable called num visits each element in order, so every element is compared with value. No index is needed because only the values matter.
    2. Compare inside the loop. If num equals value, return true. A return ends the whole function at once, so the elements after the match are never examined.
    3. Return false after the loop. The only way to reach that line is to have gone through the entire array without a match, so no else is required.

    The solution in Kotlin

    class Solution {
        fun contains(nums: IntArray, value: Int): Boolean {
            for (num in nums) {
                if (num == value) {
                    return true
                }
            }
            return false
        }
    }
    

    Kotlin details worth knowing:

    • for (num in nums). The loop variable num is a read-only value that takes each element in turn. Arrays can be looped over directly, with no .length or index arithmetic.
    • == compares values. For numbers, num == value checks that they are equal. For objects such as strings, Kotlin's == calls equals and compares contents, and === is the operator that compares references. Plain Int comparisons need no care.
    • The return type must always be reached. The function is declared to return a Boolean, and the compiler checks that every path ends in a return. If the final return false is missing, the code is rejected with missing return statement, even though the loop could return.
    • Ready-made helpers exist. Kotlin has a built-in contains (the in operator) for arrays and collections. The exercise asks you to write the loop yourself so you learn what that helper does.

    Complexity

    Time: O(n), where n is the number of elements. In the worst case the value is last or absent, and every element is compared once. If the value is the first element, the function returns after one comparison.

    Space: O(1). The function stores only the loop variable.

    Edge cases and common mistakes

    • Empty array. The loop body never runs and the function returns false, which is right: nothing can be found in an empty array.
    • Returning false too early. Putting else { return false } inside the loop compares only the first element. For [1, 2, 4, 5] and 4 it would answer false after seeing 1.
    • Duplicates. The first match ends the search, so repeated values cost nothing extra.
    • Negative numbers and zero. They are ordinary values. [-1, 2, -4, 0, 10] contains 0 and -4, and the comparison treats them like any other number.
    • The value at the end. A match at the last position is found only by the final pass of the loop. Stopping one element early is an easy off-by-one error when you manage the index by hand.

    Testing

    • nums = [1, 2, 4, 5], value = 4 gives true.
    • nums = [-1, 2, -4, 0, 10], value = 7 gives false.
    • nums = [], value = 7 gives false.
    • nums = [-1, 2, -4, 0, 10], value = 10 gives true.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free