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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay