0
\$\begingroup\$

I have the following code:

const arr = Array.from({length: 5}, (_, i) => i + 1);
const finalArray = [];
for (let i = 0; i < arr.length; i++) {
 for (let j = 0; j < arr.length; j++) {
 finalArray.push(arr[i] + '-' + arr[j])
 }
}
console.log(finalArray);

Which creates an array of range 1 => 5, and returns an array with a combination of all elements in the original array.

This code runs in O(n2), is it possible to make it more efficient?

asked Feb 20, 2021 at 15:04
\$\endgroup\$
1
  • 1
    \$\begingroup\$ The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How do I ask a good question?. \$\endgroup\$ Commented Feb 23, 2021 at 8:35

1 Answer 1

3
\$\begingroup\$

No

You cannot output \$\Theta(n^2)\$ items in \$o(n^2)\$ time. Output size is a trivial lower bound of any algorithms.

answered Feb 23, 2021 at 7:41
\$\endgroup\$
2
  • \$\begingroup\$ So you mean that my code is most performant? \$\endgroup\$ Commented Feb 23, 2021 at 12:30
  • 1
    \$\begingroup\$ @callback from the view of big-O notation: Yes. To improve its performance: Maybe No. \$\endgroup\$ Commented Feb 24, 2021 at 1:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.