Input: arr[] = [-4, -2, 0, 2, 4], A = 1, B = 3, C = 5
Output: [3, 5, 9, 15, 33]
Explanation: After applying f(x) = 1*(x^2)+ 3*x + 5 to each x, we get [3, 5, 9, 15, 33]. After sorting this array, the array becomes [3, 5, 9, 15, 33].
Input: arr[] = [-3, -1, 2, 4], A = -1, B = 0, C = 0
Output: [-16, -9, -4, -1]
Explanation: After applying f(x) = -1*(x^2) to each x, we get [ -9, -1, -4, -16 ]. After sorting this array, the array becomes [-16, -9, -4, -1].
Input: arr[] = [-1, 0, 1, 2, 3, 4], A = -1, B = 2, C = -1
Output: [-9, -4, -4, -1, -1, 0]
The idea is to use the fact that input array is sorted and apply a Two-Pointer approach. After applying the quadratic transformation to each element, the smallest and largest values will always be at the ends of the array (Why? The equation given is parabolic. So the result of applying it to a sorted array will result in an array that will have a maximum/minimum with the sub-arrays to its left and right sorted)
We process from both ends using two pointers (left and right) moving towards each other. By comparing the transformed values of arr[left] and arr[right], we can fill a new array (newArr) starting either from the front or the back depending on whether the coefficient A is positive or negative. The observation here is:
- if A >= 0, the largest values will be at the end
- while if A < 0, the largest values will be at the beginning.