0

I'm writing this function in order to identify the first missing element from the array. I want to return the missing element but I'm getting a Unit

I can't identify what am I missing

def missingElement(a : Array[Int]) : Int = {

  val result =for (i <- 1 to a.length) {
    if(! a.contains(i)) {
      i
    } 
  }
  result

}

1 Answer 1

3

"identify the first" is a find operation, so the code might look like this:

def missingElement(a: Array[Int]): Option[Int] = 
  a.indices.find(i => !a.contains(i+1))

This returns an Option because there might not be a missing element, in which case it will return None, otherwise it will return Some(n).

Sign up to request clarification or add additional context in comments.

2 Comments

this is an out of context question, but is there a way to measure time and space complexity in scala?
There is no automatic way. A starting point is this article which gives the complexity of various operations on the main collection types in the standard library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.