![]() |
VOOZH | about |
Given an array of strings arr[] and an array cost[] representing the cost to reverse each corresponding string. We are not allowed to move or reorder the strings in the array, we can only reverse individual strings if needed. The task is to choose which strings to reverse such that the final array is in non-decreasing lexicographic order, and the total cost of reversals is minimized.
Note: If it's not possible to achieve a sorted array using any combination of reversals, return -1.
Examples:
Input: arr[] = ["aa", "ba", "ac"], cost[] = [1, 3, 1]
Output: 1
Explanation: The minimum cost to make the array sorted lexicographically is 1.
-> "aa" at index 0 is fine, whether reversed or not, as "aa" remains the same.
-> "ba" at index 1 is greater than "aa", so it's already in correct order.
-> "ac" at index 2 is less than "ba", so the array is not sorted. Reversing "ac" gives "ca", which is greater than "ba", making the array ["aa", "ba", "ca"] sorted. This single reversal costs 1, and no other reversal option gives a better result.Input: arr[] = ["cba", "bca", "aaa"], cost[] = [1, 2, 3]
Output: -1
Explanation: No combination of reversals can make the array sorted in lexicographic order. Even reversing all strings results in ["abc", "acb", "aaa"], which is also not sorted. Hence, the output is -1.
Table of Content
At each index i, we have two choices:
arr[i] as-isarr[i] (with cost cost[i])We recursively decide which choice to make, such that:
arr[i] is lexicographically ≥ the previous chosen string.The idea is to use dynamic programming. We maintain a 2D dp table where dp[i][0] means the minimum cost to keep i-th string as it is and dp[i][1] means the cost if it's reversed. The observation is that a string can only follow the previous one in the list if it's lexicographically greater than or equal to it (either reversed or not). We try both cases at every index and update the cost only if the order is maintained, and finally return the minimum of both states at the last index.
1
The idea is to reduce space complexity by avoiding the use of a full 2D dp array. Instead of storing the minimum costs for all indices, we only track the previous state using two variables, which is sufficient for the current computation. This optimization brings down the space complexity from O(n) to O(1).
Steps to implement the above idea:
1