title: Scala data structure and complexity O(1)
body: <p>Today I had an interview about Scala and request was:</p>
  
  <p>Implement a data structure with fixed size N , with these functionalities:</p>
  
  <ul>
  <li>get(index)</li>
  <li>set(index,value)</li>
  <li>setall(value)</li>
  </ul>
  
  <p><strong>The complexity should be O(1)</strong></p>
  
  <pre><code>example:
     val ds = DS(100)
     ds.set(4,5)
     ds.get(4) //would return  5
     ds.set(1,4)
     ds.setall(10)
     ds.get(4) //would return  10
     ds.get(7) //would return  10
     ds.set(1,7)
     ds.get(1) //would return  7
  </code></pre>
  
  <p>Please find code that I have sent below.<br>
  My question would be <strong>Is this right solution and if there is a better way of doing it ?</strong></p>
  
  <pre><code>import scala.collection.mutable.HashMap
  
  trait Operations {
  
    def get(index: Int): Int
    def set(index: Int, value: Int)
    def setall(value: Int)
  }
  
  class DS(N: Int) extends Operations {
  
    var myMutableHashMap = new HashMap[Int, Int]().withDefaultValue(0)
  
    def get(index: Int) = myMutableHashMap(index)
  
    def set(index: Int, value: Int) = {
      if (index &lt;= N) myMutableHashMap += (index -&gt; value)
    }
  
    def setall(value: Int) = {
  
      myMutableHashMap = new HashMap[Int, Int]().withDefaultValue(value)
    }
  
  }
  
  object Task {
  
    def main(args: Array[String]): Unit = {
  
      val ds = new DS(100)
  
      ds.set(4, 5)
      ds.get(4)
  
      println(ds.get(4)) // -&gt; 5
  
      ds.setall(10)
      println(ds.get(4)) //-&gt; 10
      println(ds.get(7)) //-&gt; 10
      ds.set(1, 7)
      println(ds.get(1)) //-&gt; 7
  
    }
  
  }
  </code></pre>