VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construction-of-multiple-ap-arrays/

⇱ Construction of multiple AP Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construction of multiple AP Arrays

Last Updated : 19 Oct, 2023

Given an array A[] of N integers, the task is to check if it is possible to construct several arrays (at least one) using all the elements of the array A[] such that in each array, the value of each element is equal to the number of elements to its left.

Examples:

Input: N = 9, A[] = {0, 0, 0, 0, 1, 1, 1, 2, 2}
Output: YES
Explanation: The array A[] can be divided into 4 arrays as follows -

  • {0,1,2} -> 1st element (0) has 0 elements to its left, 2nd element (1) has 1 element to its left and 3rd element (2) has 2 elements to its left
  • {0,1} -> 1st element (0) has 0 elements to its left and 2nd element (1) has 1 element to its left
  • {0,1,2} -> 1st element (0) has 0 elements to its left, 2nd element (1) has 1 element to its left and 3rd element (2) has 2 elements to its left
  • {0} -> 1st element (0) has 0 elements to its left

Input: N = 3, A[] = {0, 0, 2}
Output: NO

Approach: To solve the problem follow the below observations:

Observation:

  • The problem can be rephrased as " Is it possible to divide input array in Arithmetic Progressions each having the first digit 0 and a common difference equal to 1 "?
    • For each A.P., if an integer X is a part of it, then X-1 must also be there. So, in the whole sequence if X occurs "count" times, then X-1 must also occur at least count times.

Following is the code based on the above approach:


Output
YES

Time Complexity: O(N).
Auxiliary Space: O(N)

Comment
Article Tags: