0

I'm working on a project using Java and am creating an object which has a 2D array of primitive values as one of its instance variables. I'm hoping to create a method which initializes the object's instance variables in O(n) time complexity, but I'm unsure if this is possible as my understanding of 2D array initialization is that it takes O(n2), as a 2D array is essentially an array of arrays, and initializing a 1D array in Java takes O(n) time. I was hoping to confirm whether or not this belief and reasoning is correct.

Thank you in advance!

  • 3
    `O(n^2)` is correct for an array of dimensions `[n][n]`. But I'm curious why it matters. – shmosel Dec 27 '21 at 20:59
  • @shmosel Thank you very much. To be honest, it really doesn't in this specific case: the 2D array I'm creating is 6 x 7, so it's small enough where it wouldn't make much of a difference. The main reason I asked is because I'm trying to learn efficient coding practices, and I'm practicing by trying to keep my methods and functions at a maximum time complexity of O(n log n) whenever possible. –  Dec 27 '21 at 21:04
  • ["*premature optimization is the root of all evil*" -- Donald Ervin Knuth: *Computer Programming as an Art* (1974), p. 671](https://dl.acm.org/ft_gateway.cfm?id=361612&ftid=289767) – Turing85 Dec 27 '21 at 21:06
  • Time complexity is O(n) if there are n elements total. There is nothing special about a 2D array – Bohemian Dec 27 '21 at 21:32
  • A tip: a homogenous matrix of _n_ rows and _m_ columns can be represented as a 1d array of _n * m_ elements. Imagine laying all of the rows end to end. Instead of accessing elements as `array[i][j]`, you can access them as `array[i * n + j]`. – Tim Moore Dec 27 '21 at 22:32

0 Answers0