-3

how to get all the subarrays in O(nlog(n)) time complexity using javaScript

I try with a nested loop but the time complexity is in O(n*n). I heard about some prefix solutions but have no information

Ujjwal
  • 1
  • 3
  • we also have no information of your code and what the problem might be if we don't even see it – Chris G Feb 10 '23 at 17:06
  • Like Chris already said - we need some more context to help you out. Maybe this older thread answers your question (partially)? https://stackoverflow.com/questions/39525266/find-all-subarrays-in-on-time-1d-array-using-javascript – Schabbi Feb 10 '23 at 17:10
  • I don't think it can be done in nlogn. You can do it with nlogn iterations, but each iteration has to make a copy of the subarray, which takes time depending on the length of the subarray. – Barmar Feb 10 '23 at 17:26

2 Answers2

0

try this code :

 fetechArray = (array) => {
    for ( let subarray of array ){
      // ur code here
      fetechArray(subarray);
    }
}
  • `subarray` is an array element, not an array. How can you call the function recursively on that? There's also no base case that stops the recursion. – Barmar Feb 10 '23 at 17:23
0

Use the "divide & conquer" approach. You first divide the original array into two halves, then combine the results from both halves to get all subarrays.

function subArrays(arr) {
  if (arr.length === 1) {
    return [arr];
  }

  const mid = Math.floor(arr.length / 2);
  const left = arr.slice(0, mid);
  const right = arr.slice(mid);

  const leftSubArrays = subArrays(left);
  const rightSubArrays = subArrays(right);

  return merge(leftSubArrays, rightSubArrays);
}

function merge(left, right) {
  const result = [];

  for (let i = 0; i < left.length; i++) {
    for (let j = 0; j < right.length; j++) {
      result.push(left[i].concat(right[j]));
    }
  }

  return result;
}
Daniel
  • 49
  • 1