Xavier Chretien
Posted on January 7, 2020
- Difficulty: Easy
- Programming language: Kotlin
Problem
A fixed point in an array is an element whose value is equal to its index.
Given a sorted array of distinct elements, return a fixed point, if one exists. Otherwise, return false
.
For example:
- Given
[-6, 0, 2, 40]
, you should return2
- Given
[1, 5, 7, 8]
, you should returnfalse
My solution
This is an easy one and I don't want to go to a very complex solution. Let's just iterate the array and find the fixed point 😄
/**
* Find each fixed point in a sorted array.
*
* @param array, sorted array
* @return an list with each fixed points, the list is empty if there is no fixed points.
*/
fun findFixedPoint(array: IntArray): List<Int>{
if(array[1] < array[0]) throw IllegalArgumentException("Array not sorted")
val pointFixedFound = mutableListOf<Int>()
for ((index, value) in array.withIndex()) {
if(index == value){
pointFixedFound.add(index)
}
}
return pointFixedFound.toList()
}
UPDATED VERSION
As
suggests in the comments, I didn't really follow the question asked. The question is to return A fixed point not all fixed points, so there is the updated version (thanks again to Nick Holmes).
fun findFixedPoint(array: IntArray): Int? {
val pointFixedFound = mutableListOf<Int>()
for ((index, value) in array.withIndex()) {
if(index == value){
return index
} else if (value > index) {
break
}
}
return null
}
The function returns null if there is no fixed point because I didn't find if this is possible to return an int or false in Kotlin, so I return null instead.
Posted on January 7, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.