FastPrepFastPrep
Problem Brief

Split and Sort Array

OA
See Google online assessment and hiring insights

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 Description

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.

1Example 1

Input
A = [1, 3, 2, 4]
Output
2
Explanation
The function should return 2, as there are two ways to split the array into two parts that result in a sorted array after sorting and rejoining: • left = [1], right = [3, 2, 4] • left = [1, 3, 2], right = [4]

2Example 2

Input
A = [3, 2, 10, 9]
Output
1
Explanation
The function should return 1, as there is only one way to split the array into two parts that result in a sorted array after sorting and rejoining: • left = [3, 2], right = [10, 9]

3Example 3

Input
A = [5, 5, 5]
Output
2
Explanation
The function should return 2, as there are two ways to split the array into two parts that result in a sorted array after sorting and rejoining: • left = [5], right = [5, 5] • left = [5, 5], right = [5]

4Example 4

Input
A = [3, 1, 2]
Output
0
Explanation
The function should return 0, as there are no ways to split the array into two parts that would result in a sorted array after sorting and rejoining.

Constraints

Limits and guarantees your solution can rely on.

  • 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].
public int splitAndSort(int[] A) {
  // write your code here

}
Input

A

[1, 3, 2, 4]

Output

2

Sign in to submit your solution.