-2

Question 1. Is it ok if We use a higher-order function like map, filter, reduce to avoid nested loop?

Question 2. Is HOF is more efficient in time complexity stuff?

  • 1
    They're identical in time complexity to a for loop. But please be more specific: how are you using them to avoid specifically nested loops? They imitate loops, but not nested ones, unless you're nesting these method calls inside each other, in which case you're ultimately still nesting your loops, just hidden behind method calls. – IceMetalPunk Jun 27 '19 at 20:53
  • 3
    Of course it's OK to use them, that's what they're there for. – Barmar Jun 27 '19 at 20:53
  • A loop is a loop; those functions iterate through arrays just like `for` loops do. Didn't you just ask this same question a short time ago? – Pointy Jun 27 '19 at 20:55
  • So it's all same whether I use HOF or for loop. I need to use a different structure for that particular problem. – Amey Zulkanthiwar Jun 27 '19 at 20:57

1 Answers1

0

It's okay, but it's not really "more efficient" it's still essentially a nested operation.

in big O notation, either a nested for to get the data versus a HOF is still O(n^2).

https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/big-o-notation

Morris Buel
  • 126
  • 1
  • 8
  • 1
    A nested loop is not necessarily O(n²) – Jonas Wilms Jun 27 '19 at 21:02
  • When would nesting a loop not be? – Morris Buel Jun 27 '19 at 21:06
  • There are a lot of time complexities O(1), O(n), O(n²), O(n!), O(n log n),..., but there are *just loops*. Therefore there are many loops that are not O(n²) ... – Jonas Wilms Jun 27 '19 at 21:07
  • According to this: https://stackoverflow.com/questions/362059/what-is-the-big-o-of-a-nested-loop-where-number-of-iterations-in-the-inner-loop -> the majority of answers agree with what I wrote. When you nest a for, you square the n. Do you have documentation to show a case where a nested for would not be O(n2)? – Morris Buel Jun 27 '19 at 21:09
  • They are talking about a specific case. Not about the general case, so they are not agreeing to anyone here. `while(false) while(false)` would be a trivial example. I can give many more upon request. – Jonas Wilms Jun 27 '19 at 21:10
  • 1
    The question could be clearer, but assuming that all algorithms used in the `for` and in the HOF are the ones most suited for the task (eg, not overly complex), it's true that using a HOF vs a `for` loop (or a nested `for`) does not improve (or increase) complexity. HOF should be preferred for *readability*, not for performance – CertainPerformance Jun 27 '19 at 21:26