#2811

Check if it is Possible to Split Array

Medium
ArrayDynamic ProgrammingGreedyGreedyDynamic ProgrammingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages a greedy approach. We can track the sum of the elements and check if we can form good arrays by accumulating elements until we reach or exceed m, then reset for the next array.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable to keep track of the current sum and a counter for good arrays.
  2. 2Step 2: Iterate through the array and add each element to the current sum.
  3. 3Step 3: Whenever the current sum reaches or exceeds m, increment the good array counter and reset the current sum.
  4. 4Step 4: If the good array counter reaches n (the length of nums), return true.
  5. 5Step 5: After the loop, check if the counter is equal to n; if not, return false.
solution.py9 lines
1def canSplit(nums, m):
2    current_sum = 0
3    good_arrays = 0
4    for num in nums:
5        current_sum += num
6        if current_sum >= m:
7            good_arrays += 1
8            current_sum = 0
9    return good_arrays >= len(nums)

Complexity note: The time complexity is O(n) because we only traverse the array once, accumulating sums and counting good arrays.

  • 1The sum of elements is crucial for determining if an array can be split into good arrays.
  • 2Tracking the number of good arrays formed helps in deciding the outcome.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.