- 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.
Top comments (2)
As a constructive critique of your solution:
A)
You are claiming the array is not sorted if the first two elements are not sorted. What about the array [1, 3, 2] or [1, 1, 2]? Also, what if the array is of length 0 or 1?
You weren't asked to validate that the array was sorted, so you could simply remove this line.
B)
You are asked to return either an integer or a false, but you are returning a list. Although your list contains the answer, if this was an interview question, I would mark you down on this - demonstrating the ability to extract all detail out of a provided specification is important.
C)
Finally, given that this is coding challenge, and that we are told that input list is sorted and distinct, I think a "more optimal" solution is evident;
as soon as you find a cell value equal to the index, just return the value - no need to go to the end of the list.
as soon as you find a cell value greater than the index, just return false - there can be no fixed points from here on.
First, thank you for your critique! 😃
A) About the first line, you are right I could simply remove that line.
B) In an interview, I would probably follow the problem asked without any modification. In that case, I choose to return every fixed point on the given array but you are right I should just respect the problem.
C) I will update the post with your proposition
Once again thank you I really appreciate your comment 😃