
Kotlin
Leetcode: Single Number (Kotlin)
December 28, 2024
Leetcode: Single Number (Kotlin)
Single Number is an easy question on Leetcode. I will discuss the problem and my solution below. Single Number - LeetCode
Problem Statement
Examples
Constraints
Brainstorm
The solution I thought of is pretty straightforward.
-
They give us an array of integers, so we can use a map that will store each number as the key and the count of that number as the value.
-
We iterate through the array to set each number’s count in the map.
-
We will then iterate through the array again, but this time we will check each number’s count in the map and return the number with the count of one
They guarantee a number with a count of one is in the given array, so you could technically return any number at the end because it should never get to that point. I use Int.MIN_VALUE.
Solution
class Solution {
fun singleNumber(nums: IntArray): Int {
val map = mutableMapOf<Int, Int>()
for(num in nums){
map[num] = map.getOrDefault(num, 0) + 1
}
for(num in nums){
map[num]?.let{
if(it == 1) return num
}
}
return Int.MIN_VALUE
}
}