Sort Transformed Array

Updated on 03 July, 2025
Sort Transformed Array header image

Problem Statement

The task is to transform a provided sorted integer array nums using a quadratic function specified by the parameters a, b, and c. The quadratic function is defined as f(x) = ax^2 + bx + c. After applying this function to each element in the array, the resultant array should also be sorted before returning. This problem touches on both the application of mathematical functions to dataset transformations and the maintenance of order in computational data processing.

Examples

Example 1

Input:

nums = [-4,-2,2,4], a = 1, b = 3, c = 5

Output:

[3,9,15,33]

Example 2

Input:

nums = [-4,-2,2,4], a = -1, b = 3, c = 5

Output:

[-23,-5,1,7]

Constraints

  • 1 <= nums.length <= 200
  • -100 <= nums[i], a, b, c <= 100
  • nums is sorted in ascending order.

Approach and Intuition

The problem revolves around applying the quadratic function to each element of the sorted array and ensuring the transformed array is sorted. Here is a simple breakdown of how to approach this problem:

  1. Understand the Function Effect: Depending on the signs and values of a, b, and c, the function can exhibit different behaviors:

    • If a > 0, the function is a upwards opening parabola.
    • If a < 0, the function is a downwards opening parabola.
    • The coefficient b shifts the parabola left or right, and c provides a vertical shift.
  2. Transformation of Array:

    • For each element x in nums, compute f(x) = ax^2 + bx + c.
    • This transformation should be straightforward since the function is given and the inputs are restricted (nums are already sorted and within a specified range).
  3. Sorting the Transformed Array: Although nums is initially sorted, the transformation can change the order depending on the parameters of the function. After applying the function:

    • Iterate over the transformed results. If a is positive or zero, the function's minimum point is at the left end of the dataset, and the parabola opens upwards, meaning values will grow as x becomes large.
    • If a is negative, you might need to reverse the array since the values will decrease as x increases.
  4. Return the Sorted Transformed Array:

    • Utilize a sorting algorithm or language built-ins if available. Given the constraints (nums.length up to 200), even simpler sorting algorithms would be efficient enough.
  5. Edge Cases: Consider special cases such as when all coefficients are zero which means each element in nums will be augmented by c, or if a and b are zero which results in an array where all elements are c.

Using the example where nums = [-4,-2,2,4], a = 1, b = 3, and c = 5, the computation proceeds as f(-4) = 1*(-4)^2 + 3*(-4) + 5 = 16 - 12 + 5 = 9 and similarly for other elements. The nature of the quadratic function requires us to carefully manage the transformation and subsequent sorting to ensure the results meet the expectations.

Solutions

  • C++
cpp
class Solution {
public:
    int calculateTransformedValue(int& element, int& coeff_a, int& coeff_b, int& coeff_c) {
        // This function applies the quadratic transformation to the given element
        return (coeff_a * element * element) + (coeff_b * element) + coeff_c;
    }
    
    vector<int> sortAndTransformArray(vector<int>& arr, int a, int b, int c) {
        vector<int> transformedArray;
        int start = 0, end = arr.size() - 1;
            
        if (a < 0) {
            while (start <= end) {
                int startValue = calculateTransformedValue(arr[start], a, b, c);
                int endValue = calculateTransformedValue(arr[end], a, b, c);
                if (startValue < endValue) {
                    transformedArray.push_back(startValue);
                    start++;
                } else {
                    transformedArray.push_back(endValue);
                    end--;
                }
            }
        } else {
            while (start <= end) {
                int startValue = calculateTransformedValue(arr[start], a, b, c);
                int endValue = calculateTransformedValue(arr[end], a, b, c);
                if (startValue > endValue) {
                    transformedArray.push_back(startValue);
                    start++;
                } else {
                    transformedArray.push_back(endValue);
                    end--;
                }
            }
            reverse(transformedArray.begin(), transformedArray.end());
        }
        return transformedArray;
    }
};

The provided C++ code defines a set of functions within a Solution class to transform and sort an array based on a quadratic equation. Here’s an overview of the tasks the code performs to achieve this:

  • Calculate Transformed Value: Use the calculateTransformedValue function to apply the transformation ax^2 + bx + c to each element of the given array, where a, b, and c are coefficients passed to this function along with the array element x.

  • Sort and Transform Array: sortAndTransformArray takes an input array and coefficients a, b, c. Depending on the sign of coefficient a, the function selects different approaches to sort the transformed array:

    • If a is negative, the function generates the transformed values starting from both ends of the array moving towards the center, deciding at each step whether the start or end value gets added to the result array based on which is smaller.
    • If a is non-negative, it essentially chooses values in an opposite manner compared to when a is negative, and finally reverses the array to ensure the elements are sorted correctly.
  • Handling Edge Cases: Efficient use of array indices manages transformations by comparing values from opposite ends of the array and appending based on the evaluated conditions. This is particularly useful for accommodating quadratic function properties where the smallest or largest values can be at the ends of the transformed parabola.

The class elegantly solves the problem of sorting a transformed array using a tailored approach based on the nature of quadratic equations, optimizing for both ascending and descending transformations. The final sorted array is then produced by intelligently placing transformed elements in sequential order using conditional logic.

  • Java
java
class Solution {
    private int calculate(int element, int factor1, int factor2, int constant) {
        // Compute using quadratic formula
        return (factor1 * element * element) + (factor2 * element) + constant;
    }
    
    public int[] rearrangeSortedArray(int[] elements, int factor1, int factor2, int constant) {
        int[] transformedArray = new int[elements.length];
        int start = 0, end = elements.length - 1;
        int insertIdx = 0;
            
        if (factor1 < 0) {
            // Handle negative factor for parabolic transformation
            while (start <= end) {
                int leftCalculated = calculate(elements[start], factor1, factor2, constant);
                int rightCalculated = calculate(elements[end], factor1, factor2, constant);
                if (leftCalculated < rightCalculated) {
                    transformedArray[insertIdx++] = leftCalculated;
                    start++;
                } else {
                    transformedArray[insertIdx++] = rightCalculated;
                    end--;
                }
            }
        } else {
            // Handle positive or zero parabolic coefficient
            while (start <= end) {
                int leftCalculated = calculate(elements[start], factor1, factor2, constant);
                int rightCalculated = calculate(elements[end], factor1, factor2, constant);
                if (leftCalculated > rightCalculated) {
                    transformedArray[insertIdx++] = leftCalculated;
                    start++;
                } else {
                    transformedArray[insertIdx++] = rightCalculated;
                    end--;
                }
            }
            // Invert array for non-negative a
            for (int i = 0; i < transformedArray.length / 2; i++) {
                int temp = transformedArray[i];
                transformedArray[i] = transformedArray[transformedArray.length - i - 1];
                transformedArray[transformedArray.length - i - 1] = temp;
            }
        }
        return transformedArray;
    }
}

This Java solution focuses on applying a quadratic transformation to an array and reordering it based on a transformation rule dependent on the quadratic coefficients factor1, factor2, and constant. The function calculate(int element, int factor1, int factor2, int constant) computes the value for an array element using the specified quadratic equation.

The rearrangeSortedArray(int[] elements, int factor1, int factor2, int constant) function performs the core of the operation. It initializes an array transformedArray to hold results and uses two pointers start and end to iterate through the input array elements.

  • For a negative factor1, the function processes elements from both ends toward the center, placing the smaller of the two calculated values first. This approach leverages the properties of a downward-opening parabola.
  • For non-negative factor1, it similarly processes from both ends but places the larger of the two calculated values first, guaranteeing that the resultant array is initially sorted in reverse order due to the properties of an upward-opening or linear behavior. The array is then reversed to ensure correct ascending order.

In-depth manipulations such as inversion of the array for non-negative values of factor1 guarantee that the final output adheres to the desired order irrespective of the quadratic coefficients. This design cleverly integrates mathematical properties with array manipulation techniques to achieve the desired transformation and ordering efficiently.

  • JavaScript
js
// Compute quadratic transformation for the input value 'num'
let quadraticTransform = (num, coeffA, coeffB, coeffC) => (coeffA * num * num) + (coeffB * num) + coeffC;
    
let reorderTransformedArray = function(elements, coeffA, coeffB, coeffC) {
    let transformedElements = [];
    let start = 0, end = elements.length - 1;
        
    if (coeffA < 0) {
        while (start <= end) {
            const startTransform = quadraticTransform(elements[start], coeffA, coeffB, coeffC);
            const endTransform = quadraticTransform(elements[end], coeffA, coeffB, coeffC);
            if (startTransform < endTransform) {
                transformedElements.push(startTransform);
                start++;
            } else {
                transformedElements.push(endTransform);
                end--;
            }
        }
    } else {
        while (start <= end) {
            const startTransform = quadraticTransform(elements[start], coeffA, coeffB, coeffC);
            const endTransform = quadraticTransform(elements[end], coeffA, coeffB, coeffC);
            if (startTransform > endTransform) {
                transformedElements.push(startTransform);
                start++;
            } else {
                transformedElements.push(endTransform);
                end--;
            }
        }
        transformedElements.reverse();
    }
    return transformedElements;
};

Sort Transformed Array in JavaScript involves creating a quadratic equation to transform each element of an array and then sorting the results based on specific conditions. Here's how you can understand and execute the provided JavaScript code for this task:

  • Define a quadraticTransform function that calculates the quadratic transformation of a number provided as an input. The function uses coefficients A, B, and C to compute the transformation according to the formula: (Ax^2 + Bx + C).

  • Implement the reorderTransformedArray function, which accepts an array of elements and coefficients A, B, and C. The function processes the transformation and sorting of the array based on the sign of coefficient A:

    • If coefficient A is negative, proceed to add transformed elements in ascending order:
      • Compare transformations of start and end elements of the array.
      • Push the smaller transformation result to transformedElements and adjust the indices accordingly (increment start or decrement end).
    • If coefficient A is positive, proceed similarly but insert elements to later reverse the entire transformedElements array to maintain descending order of transformations:
      • Again, compare transformations of start and end elements, choose the larger result.
      • Push the selected transformation to transformedElements.
      • Perform a reverse operation once all elements are processed to ensure the order from highest to lowest transformation.
  • Return the transformedElements array, which now holds the correctly sorted transformations based on the specified conditions.

Adopt these strategies carefully to successfully transform and reorder arrays as required by quadratic conditions in an efficient manner. This method efficiently handles varying conditions based on the dominant coefficient, ensuring optimally transformed and ordered output.

  • Python
python
class Solution:
    def transformedArray(self, values: List[int], p: int, q: int, r: int) -> List[int]:
        def calculate(y):
            return (p * y * y) + (q * y) + r
    
        result = []
        start, end = 0, len(values) - 1
            
        if p < 0:
            while start <= end:
                start_val = calculate(values[start])
                end_val = calculate(values[end])
                if start_val < end_val:
                    result.append(start_val)
                    start += 1
                else:
                    result.append(end_val)
                    end -= 1
        else:
            while start <= end:
                start_val = calculate(values[start])
                end_val = calculate(values[end])
                if start_val > end_val:
                    result.append(start_val)
                    start += 1
                else:
                    result.append(end_val)
                    end -= 1
            result.reverse()
        return result

The provided Python code defines a method called transformedArray within a class Solution. This method undertakes the task of sorting a transformed array based on the quadratic equation p * y^2 + q * y + r. Here, values is the input list of integers, and p, q, and r are coefficients.

  • When invoked, the transformedArray function first defines a nested function calculate(y) that computes the quadratic transformation for a given integer y.
  • The solution exploits a two-pointer approach to sort the transformed values. Depending on the sign of p, the sorted order of transformation is determined:
    • If p is negative, the transformed values appear naturally in ascending order because the vertex of the parabola faces downwards.
    • For non-negative p, the vertex faces upwards, producing values in descending order, thus requiring a reverse at the end to get the array in ascending order.
  • Using two pointers, start and end, which initialize at the beginning and end of the input array values, the function proceeds to compare transformed values from both ends:
    • If p is negative, the smaller transformed value between start and end is appended and the corresponding pointer is incremented or decremented.
    • If p is non-negative, the larger value is taken, appended to the result list, and the list is reversed at completion.

This method effectively considers all edge cases and implements a clear and efficient strategy to sort the array based on the transformed values. The code exhibits efficient use of conditionals, loop constructs, and list operations forming a comprehensive solution to the described problem.

Comments

No comments yet.