KatInterview

String Reversal with Contiguous Subarray Extremes

Dynamic ProgrammingAuto-graded · 25 test cases
MediumAuto-gradedDynamic Programmingarraysstringskadane

Last 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^4
  • 1 ≤ len(nums) ≤ 10^4
  • -10^4 ≤ nums[i] ≤ 10^4
  • The array nums is 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.