Problem · Array

Split and Sort Array

Learn this problem
MediumGoogle logoGoogleNEW GRADOA
See Google hiring insights

Problem statement

You are given an array A of N integers. You can split the array into two non-empty parts, left and right, sort the elements in each part independently and join them back together.

For example, given array A = [1, 3, 2, 4], you can split it in the following three ways:

  • left = [1], right = [3, 2, 4]. Sorting the elements and joining the parts back together results in the array: [1, 2, 3, 4].
  • left = [1, 3], right = [2, 4]. Resulting sorted and rejoined array: [1, 3, 2, 4].
  • left = [1, 3, 2], right = [4]. Resulting sorted and rejoined array: [1, 2, 3, 4].

Your task is to find the number of ways of splitting the array into two parts such that, after sorting the two parts and rejoining them into a single array, the resulting array will be sorted in non-decreasing order. For the array shown above, the answer is 2: the first and third splits result in a sorted array.

Function

splitAndSort(A: int[]) → int

Write a function:

class Solution { public int solution(int[] A); }

which, given an array A of length N, returns the number of different ways of obtaining a sorted array by applying the procedure described above.

Update 06-26-2026: Find Number of Ways to Split Array is a duplicate of this problem. I recommend practicing this version because it is more complete. 🌸

Examples

Example 1

A = [1, 3, 2, 4]return = 2

Two split points produce a globally sorted array:

  1. [1] | [3, 2, 4] becomes [1] | [2, 3, 4].
  2. [1, 3, 2] | [4] becomes [1, 2, 3] | [4].

Therefore, the answer is 2.

Example 2

A = [3, 2, 10, 9]return = 1

The only valid split is:

[3, 2] | [10, 9] becomes [2, 3] | [9, 10].

The joined array is [2, 3, 9, 10], so the answer is 1.

Example 3

A = [5, 5, 5]return = 2

Every element is equal, so sorting either side never changes the array.

  • [5] | [5, 5] is valid.
  • [5, 5] | [5] is valid.

Both possible split points work, giving an answer of 2.

Example 4

A = [3, 1, 2]return = 0

Neither possible split works:

  • [3] | [1, 2] remains [3, 1, 2].
  • [3, 1] | [2] becomes [1, 3, 2].

Both joined arrays contain a decrease, so the answer is 0.

Constraints

  • N is an integer within the range [2..100,000];
  • each element of array A is an integer within the range [1..1,000,000,000].

More Google problems

drafts saved locally
public int splitAndSort(int[] A) {
  // write your code here

}
A[1, 3, 2, 4]
expected2
checking account