Number of Ways to Split Array — LeetCode 2270 Python Solution
- Problem
- #2270
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums of length n. nums contains a valid split at index i if the following are true: The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.
Example
- Input
- nums = [10,4,-8,7]
- Output
- 2
- Explanation
- There are three ways of splitting nums into two non-empty parts:
Python solution
class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
s = sum(nums)
ans = t = 0
for x in nums[:-1]:
t += x
ans += t >= s - t
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{nums} |
| Space | O(1) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2270. Number of Ways to Split Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2270. Number of Ways to Split Array?
- LeetCode 2270. Number of Ways to Split Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2270. Number of Ways to Split Array?
- The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.
- What is the space complexity of LeetCode 2270. Number of Ways to Split Array?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2270. Number of Ways to Split Array cover?
- LeetCode 2270. Number of Ways to Split Array is tagged Array and Prefix Sum on LeetCode.