Array Manipulation

  • + 0 comments

    Single Pass O(N) Functional Sol'n

    def arrayManipulation(n: Int, queries: Array[Array[Int]]): Long = 
    
      queries.foldLeft(new Array[Long](n+1)) { 
        case (darr,q) => q match {
          case Array(start, end, value) =>
            darr(start - 1) += value
            darr(end) -= value  
            darr
        }}.scanLeft(0L)(_+_).max
    

    Understand the Difference Array Trick - super simple and effective!

    1. Make arr size n+1 so we can add to end if its the Last item (or ignore)

    2. only Mark the Starts with +query and mark the end+1 index with a -ve value [100, 500 , 0 , 200 , -100 , -500 , 0 , -200 ]

    3. Then simply compute the Prefix Array in a Single Pass