String Reversal with Contiguous Subarray Extremes
Dynamic ProgrammingAuto-graded · 25 test casesLast updated
Tests string manipulation and dynamic programming through reversing text and finding optimal contiguous subarrays by sum and product.
Write a function that performs three independent operations:
Task 1: Reverse a String
Given a string s, return it with all characters in reversed order.
Task 2: Find the Largest Contiguous Subarray Sum
Given an integer array nums that may contain negative values, find the maximum sum achievable by selecting any single contiguous, non-empty subarray.
For instance, in [-2,1,-3,4,-1,2,1,-5,4], the subarray [4,-1,2,1] produces sum 6, which is optimal.
Task 3: Find the Largest Contiguous Subarray Product
Given the same integer array nums (which may also contain zeros), find the maximum product achievable by selecting any single contiguous, non-empty subarray.
For instance, in [2,3,-2,4], the subarray [2,3] produces product 6, which is optimal.
Your function must return a list containing three values: [reversed_string, max_sum, max_product].
Constraints
0 ≤ len(s) ≤ 10^41 ≤ len(nums) ≤ 10^4-10^4 ≤ nums[i] ≤ 10^4- The array
numsis guaranteed to be non-empty - Subarrays must contain at least one element
Examples
Example 1
Input: compute_string_and_subarray_metrics('hello', [-2, 1, -3, 4, -1, 2, 1, -5, 4])
Output: ['olleh', 6, 960]
Example 2
Input: compute_string_and_subarray_metrics('interview', [2, 3, -2, 4])
Output: ['weivretni', 7, 6]
Example 3
Input: compute_string_and_subarray_metrics('racecar', [-2, -3, -4])
Output: ['racecar', -2, 12]
Hints
Hint 1
For reversing a string in Python, slicing with a negative step provides an elegant one-liner solution.
Hint 2
The maximum sum problem is a classic application of Kadane's algorithm: at each position, decide whether to extend the previous subarray or start fresh.
Hint 3
For maximum product, track both the largest and smallest products ending at each position, since multiplying by a negative number can turn a very negative value into a large positive one.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines three independent tasks that test different algorithmic patterns.
Task 1: String Reversal
Python's slice notation s[::-1] iterates backward through the string, building the reversed result. This is the idiomatic approach and runs in linear time.
Task 2: Maximum Subarray Sum (Kadane's Algorithm)
We maintain current_sum, representing the best sum of any subarray that ends exactly at the current position. At each new element value, we have two choices:
- Extend the previous best subarray:
current_sum + value - Start a fresh subarray here:
value
We take whichever is larger. Since every contiguous subarray ends somewhere, tracking the maximum current_sum seen gives us the global answer.
Task 3: Maximum Subarray Product
The product case is trickier because multiplication by a negative number reverses ordering. A highly negative product can become the maximum after multiplying by another negative number.
We track two values for subarrays ending at the current position:
max_ending: the largest productmin_ending: the smallest (most negative) product
For each new value, we compute three candidates:
valuealone (starting fresh, which also handles zeros)max_ending * valuemin_ending * value
The new max_ending is the maximum of these three, and the new min_ending is the minimum. Crucially, we compute both from the old values simultaneously to avoid using an already-updated value.
Why This Works
For the sum problem, let best(i) denote the maximum sum of any subarray ending at index i. This subarray either consists of just nums[i], or extends some subarray ending at i-1. The optimal extension uses best(i-1), giving us the recurrence best(i) = max(nums[i], best(i-1) + nums[i]). The global maximum is the maximum of all best(i) values.
For the product problem, we maintain the invariant that max_ending and min_ending are the true extremes among all subarrays ending at the current position. When we multiply by a new value:
- If the value is positive, multiplication preserves order
- If the value is negative, multiplication reverses order
- If the value is zero, all products become zero
In all cases, the true extremes for position i must come from either starting fresh at i or multiplying one of the previous extremes. Taking max and min over all three candidates maintains the invariant.
Complexity
Time Complexity: O(n + m) where n is the length of the string and m is the length of the array. We make one pass through the string for reversal and one pass through the array for both subarray computations.
Space Complexity: O(n) for the reversed string output. The subarray computations use O(1) additional space since we only track a constant number of variables.
Full Solution
from typing import List
def compute_string_and_subarray_metrics(s: str, nums: List[int]) -> List[object]:
# Task 1: Reverse the string using slice notation
reversed_string = s[::-1]
# Initialize tracking variables with the first element
# (ensures non-empty subarrays)
max_sum = nums[0]
current_sum = nums[0]
max_product = nums[0]
max_ending = nums[0]
min_ending = nums[0]
# Process remaining elements
for value in nums[1:]:
# Task 2: Kadane's algorithm for maximum sum
# Either extend previous subarray or start new one
current_sum = max(value, current_sum + value)
max_sum = max(max_sum, current_sum)
# Task 3: Product variant tracking both extremes
# Compute candidates from OLD max_ending and min_ending
candidates = (value, max_ending * value, min_ending * value)
max_ending = max(candidates)
min_ending = min(candidates)
max_product = max(max_product, max_ending)
return [reversed_string, max_sum, max_product]