DEV Community

Christopher Coffee
Christopher Coffee

Posted on

1 1 1

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.

  1. 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.

  2. We iterate through the array to set each number’s count in the map.

  3. 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
}
}
view raw SingleNumber.kt hosted with ❤ by GitHub

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More