Skip to the code
+50 XP

#51 Shortest Trim to Split Evenly

hard

A ticketing system has nums[i] seats in each section, in a row. It wants to split the remaining seats evenly among p ushers, so the total must be a multiple of p. To get there, it can close one run of back-to-back sections (possibly none), but never all of them.

Write shortestTrim(nums, p) that returns the length of the shortest run to close so the remaining total is a multiple of p. Return 0 if no closing is needed and -1 if it's impossible without closing every section.

Example 1

Input: nums = [4,2,7,1], p = 5
Output: 1

The total is 14. Closing the section with 4 seats leaves 10, a multiple of 5.

Example 2

Input: nums = [2,3], p = 7
Output: -1

Closing one section leaves 3 or 2; closing both isn't allowed.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • 1 <= p <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).