Search code examples
javaarraysspace-complexity

Does memory requirement of a code consist of a arithmetic computation is greater than that of code consist of low arithmetic computation in java?


`here I am writing a solution for concatenation of two arrays using but I come up with two solutions. the problems is given as below: Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).

Specifically, ans is the concatenation of two nums arrays.

Return the array ans. Example:

Input: nums = [1,2,1] Output: [1,2,1,1,2,1] Explanation: The array ans is formed as follows:

  • ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
  • ans = [1,2,1,1,2,1]

Now,can anyone please explain me how can the space complexity of code (1) is better than that of the code (2)? Both solutions are made by me But I can't understand that how can be the time complexity of code (1) is better that of code (2). please explain this if you know how is code (1) better and taking less memory as compared to that of (2)? code (1) is taking memory of : 44.42 MB. code (2) is taking memory of : 44.72 MB. code(1) :

` class Solution { public int[] getConcatenation(int[] nums) {

 int n = nums.length;
 int[] arr = new int[2*n];
 int k = 0;
 int count = 0;
 for(int i = 0; i < n; i++){
     arr[k] = nums[i];
     k++;
     if(i == n-1){
         i = -1;
         count++;
     }
     if(count == 2){
         break;
     }
 }
 
return arr;

} }

 code (2) :
 class Solution {
 public int[] getConcatenation(int[] nums) {

 int n = nums.length;
 int[] arr = new int[2*n];

 
 for(int i = 0; i < 2*n; i++){
     arr[i] = nums[i % n];
 }
 

return arr; } }` Ask Question


Solution

  • Is 44.42/44.72 MB the memory used by the JVM during execution? Or is it the size in disc for the application?

    In any case, the JVM is not "deterministic" in that sense, ghe GIT compiler can even change the memory used during the execution.

    For Java memory management, there are tons of interesting metrics. But the one you are looking at is probably not one of them. I would suggest the following things to learn if you want to get starting understanding this field:

    • What is Stack vs. Heap.
    • Java memory management, Eden, Survivor, Tenured and other spaces.
    • Garbage collecfion.

    With your code examples, investigate how they scale if you make your array 1 kb vs 1 mb long.