I found this on leetcode someone posted the problem . I am wondering if there is a solution for followup .
Given a calculation class where you initialize values for $$$a,b,c$$$ and the following function $$$f(x) = ax^2 + bx + c$$$, and a list of numbers, apply this function to all values in the list.
class Calculation {
int a;
int b;
int c;
int[] calculate(int[] arr)
}
Followup: We want the output array to be sorted. Can we do better than $$$O(nlogn)$$$?
Your problem is simply the same as sorting an array, which is not faster than n log n if it is a comparison-based sort.
You can use Radix sort or Count sort to break the lower bound based on comparison sorting.
Yeah . I was thinking the same . Thanks for your input .
If the initial list of numbers is already sorted, then you can solve this in $$$O(n)$$$ time.
Since $$$ax^2 + bx + c$$$ is a quadratic function, it either increases until some point and then decreases (if $$$a < 0$$$) or it decreases until some point and then increases (if $$$a > 0$$$). This critical point can be found through the first derivative, i.e., $$$2ax + b = 0$$$, which solves to $$$x = \frac{-b}{2a}$$$.
So the algorithm works like this, assuming the array of numbers is sorted in non-decreasing order:
Complexity: $$$O(n)$$$ runtime, $$$O(n)$$$ auxiliary space
Correct . I came up with this solution too . But I was not sure if the array is in sorted order or not .
You said you found it on LeetCode. If this was the problem: https://leetcode.com/problems/sort-transformed-array/ then yes, the initial array is sorted.
Actually I found it in Leetcode discuss section .